ModelMapper:在运行时映射抽象类 [英] ModelMapper: mapping abstract classes during runtime
问题描述
我正在使用ModelMapper框架( http://modelmapper.org/)在Java中映射对象. 在映射包含抽象类的具体类(DTO到实体)时遇到了一个问题.
I am using ModelMapper Framework (http://modelmapper.org/) for mapping objects in Java. I have encountered a problem while mapping concrete classes (DTO to Entites) containing abstract classes.
示例:
任务有一个AbstractItems列表.
抽象项目是问题和标准.
Example:
Task has a list of AbstractItems.
AbstractItems are Question and Criteria.
public class TaskDTO {
...
private List<AbstractItemDTO> items;
}
映射方法:
// task is an TaskDTO object
return getModelMapper().map(task, TaskEntity.class);
ModelMapper尝试创建一个AbstractItem的新实例,该实例将引发异常.
有没有一种方法可以在运行时映射抽象类?
像QuestionDTO->问题,条件DTO->条件
ModelMapper tries to create a new instance of AbstractItem, which throws an exception.
Is there a way to map the abstract classes during the runtime?
Like QuestionDTO -> Question, CriteriaDTO ->Criteria
推荐答案
我无法使用ModelMapper解决此问题.因此,我切换到推土机.
推土机是Java中用于对象映射的出色工具.而且真的很容易使用.
您可以在XML文件中定义相应的映射类.
I couldn't solve this problem with ModelMapper. Thus, I switched over to Dozer.
Dozer is a great tool for object mapping in Java. And it is really easy to use as well.
You can define the corresponding mapping classes in a XML-file.
这里是文档的链接. http://dozer.sourceforge.net/documentation/mappings.html
Here's a link to the documentation. http://dozer.sourceforge.net/documentation/mappings.html
我的Spring解决方案
dozer-bean.xml
<bean class="org.dozer.spring.DozerBeanMapperFactoryBean" lazy-init="false">
<property name="mappingFiles">
<list>
<value>META-INF/mapping/dozer-config.xml</value>
</list>
</property>
</bean>
dozer-config.xml
<mapping>
<class-a>com.packagename.dto.QuestionDTO</class-a>
<class-b>com.packagename.entities.core.Question</class-b>
</mapping>
<mapping>
<class-a>com.packagename.dto.CriteriaDTO</class-a>
<class-b>com.packagename.entities.core.Criteria</class-b>
</mapping>
这篇关于ModelMapper:在运行时映射抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!