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

廷基

假设我有课MySource

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

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

我想将其翻译为object 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()]

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

无法直接使用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是否为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)

这样就被初始化了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何自定义ModelMapper

ModelMapper:在使用具有自定义映射的TypeMap时如何保持转换器在映射器级别注册

查询映射的自定义对象时出现 NullPointerException

应用程序崩溃时如何将自定义对象写入数据库?

映射列并应用自定义功能

自动映射器自定义解析器源成员到目标对象列表的映射问题

应用关闭后,如何保存自定义对象的ArrayList?

如何从OpportunityStage为自定义对象创建自定义选择列表

将派生类映射到基类时,ModelMapper 返回源对象类型

Simulink:如何提供自定义源

使用托管bean中的ModelMapper库进行自定义映射会导致NullPointerException

在Entity Framework中将对象的自定义列表映射为json

如何自定义AutoFixture有时返回Null

如何定义自定义对象映射在春季启动,而不会影响春季启动的默认对象映射器?

原则2(Symfony)带有自定义字段的结果集映射始终为null

忍者框架端点抛出试图JSON映射到自定义对象时500错误

如何在单击时在运行时为整个应用程序设置自定义主题?

如何通过自定义适配器为列表视图动态设置imageView源?

如何将自定义对象列表作为源绑定到列表框?

如何将消息从套接字流源转换为自定义域对象?

将自定义对象属性映射回原始对象

自定义属性为null IdentityUser

与Firebase同步时自定义对象

自定义数据源对象未正确创建

无法为球衣中的单个对象使用自定义对象映射器(适用于集合)

如何将JSON字段映射到自定义对象属性?

使用 JAVA 反射如何创建自定义 JSON 对象映射

在以下情况下如何将自定义对象与相应的Task映射?

如何将JSON :: Any映射到Crystal语言中的自定义对象?