【问题标题】:Modelmapper: How to apply custom mapping when source object is null?Modelmapper:当源对象为空时如何应用自定义映射?
【发布时间】:2016-06-22 14:35:01
【问题描述】:

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

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

【问题讨论】:

    标签: java modelmapper


    【解决方案1】:

    直接使用ModelMapper是不可能的,因为ModelMappermap(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&lt;D&gt; 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&lt;D&gt; 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)

    这样就被初始化了。

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 2020-06-21
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2019-10-27
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多