Modelmapper:当源对象为空时如何应用自定义映射?

Modelmapper: How to apply custom mapping when source object is null?

假设我有 class MySource:

public class MySource {
    public String fieldA;
    public String fieldB;

    public MySource(String A, String B) {
       this.fieldA = A;
       this.fieldB = B;
    }
}

我想将其翻译成对象 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 class 并覆盖 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():

Output Console: NullExampleMain.MyTarget(fieldA=null, fieldB=null)

这样就初始化好了