题
有一种方法,以推土机映射集的大小?
class Source {
Collection<String> images;
}
class Destination {
int numOfImages;
}
解决方案
编辑:我已经更新了我的答案在外地一级,而不是在类级别使用自定义转换器
有可能是其他的解决方案,但这样做将是使用自定义转换器<一种方式/ A>。我已经添加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!");
}
}
然后,声明它在一个自定义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>
通过此设置中,以下测试成功通过:
@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());
}
其他提示
下面是用于解决该与 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;
}
});
此示例使用的源和目标的类的转换器。
更多的实施例和文档可以在 http://modelmapper.org
中找到不隶属于 StackOverflow