[英]ModelMapper: How to map to a List of generic instances of known concrete type
I want to convert with the ModelMapper a List<>
to a List<T>
knowing the exact java.lang.Class
of T
.我想用ModelMapper将
List<>
转换为List<T>
知道确切的java.lang.Class
的T
。 But the ModelMapper keeps only instantiating the common parent class of T...但是 ModelMapper 只保持实例化 T 的公共父 class ...
for your context: I want to convert a list of DTO to a list of Domain, but as I do it in every Service class I extracted it in a generic abstract Service.对于您的上下文:我想将 DTO 列表转换为域列表,但是正如我在每个服务 class 中所做的那样,我将它提取到通用抽象服务中。
public class BaseClass {}
public class SubClass1 extends BaseClass {}
public <T extends BaseClass> List<T> getList(Class<T> specificClass) {
...
Type listType = new TypeToken<List<T>>(){}.getType(); // here problem
List<T> responseList = modelMapper.map(listIAlreadyHave, listType);
return responseList;
}
List<SubClass1> list = doIt(SubClass1.class);
I would like list to be a list of SubClass1
instances, but i get only BaseClass
instances.我希望 list 是
SubClass1
实例的列表,但我只得到BaseClass
实例。 I don't blame Java for not understading my listType
definition because T is unknown on runntime, but how can i use the specificClass
parameter i generously provide?我不责怪 Java 没有理解我的
listType
定义,因为 T 在运行时是未知的,但是我如何使用我慷慨提供的specificClass
参数?
Thank you dear community!谢谢亲爱的社区!
You can use explicit mapping and specify the way mapper has to convert one instance to another.您可以使用显式映射并指定映射器必须将一个实例转换为另一个实例的方式。 Didn't you meant to make SubClass1 extend BaseClass?
你不是想让 SubClass1 扩展 BaseClass 吗? If you meant to you could just take advantage of polymorphism.
如果你的意思是你可以利用多态性。
Have a good day!祝你有美好的一天!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.