7

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

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

4

1 回答 1

7

直接使用 ModelMapper 是不可能的,因为ModelMapper map(Source, Destination)方法会检查 source 是否为空,在这种情况下它会抛出异常......

看一下 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 是否为空,在这种情况下它会初始化然后调用 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)

这样就被初始化了。

于 2016-08-01T04:32:48.647 回答