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

时间:2016-06-22 14:35:02

标签: java modelmapper

假设我有课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()]

有人知道如何编写适当的转换器来实现这一目标吗?

1 个答案:

答案 0 :(得分:4)

直接使用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)

因此它被初始化。