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

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对象为空的情况。在这种情况下,MyTarget也将为空:null

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

我想以这样的方式指定自定义映射(伪代码):

如果MySource src != null,则[执行默认映射],否则[返回新的MyTarget()]

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

1个回答

10

由于ModelMapper map(Source, Destination) 方法会检查源对象是否为空,如果为空,则会抛出异常,因此不能直接使用 ModelMapper 进行转换...

请查看 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);
    }
}

它检查源是否为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)

因此它被初始化了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接