[英]Map collection size in Dozer
Is there a way to map collection size in dozer? 有没有办法在推土机中映射集合大小?
class Source {
Collection<String> images;
}
class Destination {
int numOfImages;
}
EDIT: I've updated my answer to use a custom converter at the field level instead of at the class level. 编辑:我已经更新了答案,以便在字段级别而不是在类级别使用自定义转换器。
There might be other solutions but one way to do this would be to use a Custom Converter . 可能还有其他解决方案,但是一种方法是使用自定义转换器 。 I've added getters and setters to your classes and wrote the following converter: 我已将getter和setter添加到您的类中,并编写了以下转换器:
package com.mycompany.samples.dozer;
import java.util.Collection;
import org.dozer.DozerConverter;
public class TestCustomFieldConverter extends
DozerConverter<Collection, Integer> {
public TestCustomFieldConverter() {
super(Collection.class, Integer.class);
}
@Override
public Integer convertTo(Collection source, Integer destination) {
if (source != null) {
return source.size();
} else {
return 0;
}
}
@Override
public Collection convertFrom(Integer source, Collection destination) {
throw new IllegalStateException("Unknown value!");
}
}
Then, declare it in a custom XML mapping file : 然后,在自定义XML映射文件中声明它:
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
http://dozer.sourceforge.net/schema/beanmapping.xsd">
<mapping>
<class-a>com.mycompany.samples.dozer.Source</class-a>
<class-b>com.mycompany.samples.dozer.Destination</class-b>
<field custom-converter="com.mycompany.samples.dozer.TestCustomFieldConverter">
<a>images</a>
<b>numOfImages</b>
</field>
</mapping>
</mappings>
With this setup, the following test passes successfully: 使用此设置,以下测试成功通过:
@Test
public void testCollectionToIntMapping() {
List<String> mappingFiles = new ArrayList<String>();
mappingFiles.add("com/mycompany/samples/dozer/somedozermapping.xml");
Mapper mapper = new DozerBeanMapper(mappingFiles);
Source sourceObject = new Source();
sourceObject.setImages(Arrays.asList( "a", "b", "C" ));
Destination destObject = mapper.map(sourceObject, Destination.class);
assertEquals(3, destObject.getNumOfImages());
}
Here's an approach for solving this with ModelMapper : 这是使用ModelMapper解决此问题的方法:
ModelMapper modelMapper = new ModelMapper();
modelMapper.createTypeMap(Source.class, Destination.class).setConverter(
new AbstractConverter<Source, Destination>() {
protected Destination convert(Source source) {
Destination dest = new Destination();
dest.numOfImages = source.images.size();
return dest;
}
});
This example uses a Converter for the Source and Destination classes. 本示例将Converter用作Source和Destination类。
More examples and docs can be found at http://modelmapper.org 更多示例和文档可以在http://modelmapper.org找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.