无法直接使用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)
这样就被初始化了。



