本文介绍了Modelmapper:当源对象为null时,如何应用自定义映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我拥有类 MySource :

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

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

,我想将其翻译为对象 MyTarget :

and I would like to translate it to object MyTarget:

public class MyTarget {
    public String fieldA;
    public String fieldB;
}

使用默认的ModelMapper设置,我可以通过以下方式实现它:

using default ModelMapper settings I can achieve it in the following way:

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 :

It can happen however, that MySource object will be null. In this case, MyTarget will be also null:

    ModelMapper modelMapper = new ModelMapper();
    MySource src = null;
    MyTarget trg = modelMapper.map(src, MyTarget.class); //trg = null

我想以这种方式指定自定义映射,即(伪代码):

I would like to specify custom mapping in such a way, that (pseudo code):

MySource src!= null吗?[执行默认映射]:[返回新的MyTarget()]

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

Does anybody have idea how to write an appropriate converter to achieve that?

推荐答案

无法直接使用ModelMapper,因为 ModelMapper map(Source,Destination)方法检查source是否为null,在这种情况下,它将引发异常...

It is not possible using ModelMapper directly because ModelMapper map(Source, Destination) method checks if source is null, in that case it throws an exception...

看看ModelMapper Map方法的实现:

Take a look to ModelMapper Map method implementation:

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).

It checks if source is null, in that case it initializes then it calls super map(Object source, Class<D> destinationType).

最后,您可以像这样使用自定义的映射器:

Finally, you could use your customized mapper like this:

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():

因此它已初始化.

这篇关于Modelmapper:当源对象为null时,如何应用自定义映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 10:50