gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:24:09 29 4
gpt4 key购买 nike

假设我有类 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 ? [执行默认映射] : [return new MyTarget()]

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

最佳答案

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

Output Console: NullExampleMain.MyTarget(fieldA=null, fieldB=null)

这样就初始化了。

关于java - Modelmapper:当源对象为空时如何应用自定义映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971193/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com