質問
dozer でコレクション サイズをマップする方法はありますか?
class Source {
Collection<String> images;
}
class Destination {
int numOfImages;
}
解決
編集: クラスレベルではなくフィールドレベルでカスタムコンバータを使用するように回答を更新しました。
他の解決策があるかもしれませんが、これを行う 1 つの方法は、 カスタムコンバーター. 。ゲッターとセッターをクラスに追加し、次のコンバーターを作成しました。
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