假设我有课MySource
:
public class MySource {
public String fieldA;
public String fieldB;
public MySource(String A, String B) {
this.fieldA = A;
this.fieldB = B;
}
}
我想将其翻译为object MyTarget
:
public class MyTarget {
public String fieldA;
public String fieldB;
}
使用默认的ModelMapper设置,我可以通过以下方式实现:
ModelMapper modelMapper = new ModelMapper();
MySource src = new MySource("A field", "B field");
MyTarget trg = modelMapper.map(src, MyTarget.class); //success! fields are copied
但是,可能会发生该MySource
对象null
。在这种情况下,MyTarget还将是null
:
ModelMapper modelMapper = new ModelMapper();
MySource src = null;
MyTarget trg = modelMapper.map(src, MyTarget.class); //trg = null
我想以这种方式指定自定义映射,(伪代码):
MySource src != null ? [perform default mapping] : [return new MyTarget()]
有谁知道如何编写适当的转换器来实现这一目标?
无法直接使用ModelMapper,因为ModelMapper map(Source, Destination)
方法会检查source是否为null,在这种情况下,它将引发异常。
看一下ModelMapper Map方法的实现:
public <D> D map(Object source, Class<D> destinationType) {
Assert.notNull(source, "source"); -> //IllegalArgument Exception
Assert.notNull(destinationType, "destinationType");
return mapInternal(source, null, destinationType, null);
}
我建议扩展ModelMapper类并map(Object source, Class<D> destinationType)
像这样重写:
public class MyCustomizedMapper extends ModelMapper{
@Override
public <D> D map(Object source, Class<D> destinationType) {
Object tmpSource = source;
if(source == null){
tmpSource = new Object();
}
return super.map(tmpSource, destinationType);
}
}
它检查source是否为null,在这种情况下,它将初始化,然后调用super map(Object source, Class<D> destinationType)
。
最后,您可以像这样使用自定义的映射器:
public static void main(String args[]){
//Your customized mapper
ModelMapper modelMapper = new MyCustomizedMapper();
MySource src = null;
MyTarget trg = modelMapper.map(src, MyTarget.class); //trg = null
System.out.println(trg);
}
输出将是new MyTarget()
:
输出控制台:NullExampleMain.MyTarget(fieldA = null,fieldB = null)
这样就被初始化了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句