是的,您将需要一个 CustomConverter 实现,因为无法通过直接映射在 List 的元素内设置值。
Dozer XML 需要一个简单的配置标签,引用 CustomConverter 类:
<?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">
<configuration>
<custom-converters>
<converter type="somepackage.MyConverter" >
<class-a>somepackage.A</class-a>
<class-b>somepackage.B</class-b>
</converter>
</custom-converters>
</configuration>
</mappings>
这是 CustomConverter:
public class MyConverter implements CustomConverter {
public Object convert(Object destination, Object source, Class destClass, Class sourceClass){
if (source == null) {
return null;
}
B dest = null;
if (source instanceof A) {
// check to see if the object already exists
if (destination == null) {
dest = new B();
} else {
dest = (B) destination;
}
//dest is your parentB instance
//setting indicatorB value in parentB
dest.setIndicatorB(((A) source).getIndicatorA());
//creating child instances of B
B child1B = new B();
B child2B = new B();
//setting indicatorB values to the child instances as well
child1B.setIndicatorB(((A) source).getIndicatorA());
child2B.setIndicatorB(((A) source).getIndicatorA());
//adding child Bs to parentB list
List<B> listOfBs = new ArrayList<B>();
listOfBs.add(child1B);
listOfBs.add(child2B);
dest.setListB(listOfBs);
return dest;
}
return null;
}
}
如果 childAs 的数量仅在运行时已知,您可以使用 CustomConverter 中的循环来创建相应数量的 childB。