我正在使用 Orika 1.4.6,我想使用 CustomConverter 来映射我的一个字段。当源字段为空时,似乎没有调用转换器。这是我的代码:
class From {
String source;
}
class To {
String destination = "defaultValue";
}
public class Mapper extends ConfigurableMapper {
private class MyConverter extends CustomConverter<String, String> {
@Override
public String convert(String source, Type<? extends String> destinationType) {
if (null == source) {
return "NULL!";
}
return "->" + source + "<-";
}
}
@Override
protected void configure(MapperFactory factory) {
factory.getConverterFactory().registerConverter("converter", new MyConverter());
factory.classMap(From.class, To.class)
.fieldMap("source", "destination")
.mapNulls(true)
.converter("converter")
.add()
.register();
}
}
如果我映射以下对象:
From from = new From(); //from.source == null
Mapper mapper = new Mapper();
To to = mapper.map(from, To.class);
System.out.println(to.destination);
我期望以下输出:
NULL!
但是我得到以下信息:
null
这表明根本没有调用转换器,并且只是复制了空值,因为
.mapNulls(true)
如果我现在设置
.mapNulls(false)
问题仍然存在,因为源字段中的空值被忽略,从而使目标字段保持不变(在这种情况下,值为“defaultValue”)。
例如,可以将“customize”方法与 CustomMapper 结合使用。然而,这个解决方案在我的实际应用程序中要复杂得多,因此使用 CustomConverter 的解决方案似乎更合适。
有谁知道这个特定示例中的问题出在哪里?
干杯,罗伯特