使用 Dozer 的自定义转换器将对象列表映射到另一个列表 [英] Map a list of object to another list using Dozer's custom converters

查看:26
本文介绍了使用 Dozer 的自定义转换器将对象列表映射到另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是使用 Dozer 将实体列表映射到它们的字符串 ID 列表(或多或少).

What I am trying to do is to map a List of entities to a list of their String ids (more or less) using Dozer.

显然,这意味着自定义转换器.我的第一个想法是制作一个从 MyEntity 到 String 的转换器,然后对 Dozer 说使用这个转换器映射这个集合的每个对象".但我不知道该怎么做.

Obviously, it implies Custom Converter. My first idea was to make a converter from MyEntity to a String, and then say to Dozer something like "Map every object of this collection using this converter". But I couldn't figure out how to do so.

所以我的第二个想法是让转换器直接从实体列表到字符串列表.我对这个想法的问题是,我一直在努力解决一些荒谬的事情,即在构造函数中获取我的列表的类型,如下所示(根本不起作用):

So my second idea was to make a converter form a list of entities to a list of string, directly. My problem on this idea is that I was strugling on something ridiculous which is to get the type of my list in the constructor, as below (which doesn't work at all):

public MyEntityListConverter() {
    super(List<MyEntity>.class, List<String>.class);
}

我不知道如何在不声明任何内容的情况下在一行中传递实例化列表的类.

I don't know how to pass an instantiated list's class in a single row wihout declaring anything.

所以如果有人知道:

  • 如何指定推土机在集合映射中使用的对象转换器
  • 如何获取实例化的列表类型
  • 尝试第三种/更好的解决方案

推荐答案

由于泛型类型,您尝试的方式不可行.如果是,Dozer 将无法在运行时检测类型.

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

第一个解决方案,使用List<>

您的转换器:

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

您的映射:

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));

第二种解决方案使用列表包装器

您可以尝试创建扩展列表实现的自定义类.

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.

您的转换器:

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

您的映射:

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

这篇关于使用 Dozer 的自定义转换器将对象列表映射到另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆