Map a list of object to another list using Dozer's custom converters

那年仲夏 提交于 2019-11-30 23:15:01

The way you tried is not possible due to generic types. And if it was, Dozer cannot detect types at runtime.

1st solution with List<>

Your converter :

public class MyEntityToStringConverter extends DozerConverter<MyEntity, String> {
    // TODO constructor + impl
}

Your mapping :

mapping(MyEntityA.class, MyEntityB.class)
.fields("myEntityList", "myStringList",
    hintA(MyEntity.class),
    hintB(String.class));

mapping(MyEntity.class, String.class)
.fields(this_(), this_(), customConverter(MyEntityToStringConverter.class));

2nd solution with list wrappers

You can try to create your custom classes extending a list impl.

public class MyEntityList extends ArrayList<MyEntity> {

}

public class MyStringList extends ArrayList<String> {

}

Change your field in the parent classes you want to map.

Your converter :

public class MyEntityToStringConverter extends DozerConverter<MyEntityList, MyStringList> {
    // TODO constructor + impl
}

Your mapping :

mapping(MyEntityA.class, MyEntityB.class)
.fields("myEntityList", "myStringList", customConverter(MyEntityToStringConverter.class));

Another option would be

super((Class<List<MyEntity>>) (Class<?>) List.class,(Class<List<String>>) (Class<?>) List.class);

I very much inclined to @Ludovic solution, but there might be a catch as mentioned in my comment up there.

But a slight tweak works for me though - register the custom converter in "configuration" rather than field level. I'm using XML config but it should work with coding config:

<configuration>
  <custom-converters>
    <converter type="f.q.c.n.MyEntityToStringConverter">
      <class-a>java.lang.String</class-a>
      <class-b>f.q.c.n.MyEntity</class-b>
    </converter>
  </custom-converters>
</configuration>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!