[英]Dozer mapping from Set<Object> to List<ENUM>
I want to map a Set of objects to a List of Enums. 我想将一组对象映射到枚举列表。 I have already created a custom converter to convert enums to their string equivalents.
我已经创建了一个自定义转换器,将枚举转换为等效的字符串。 When I try to run Junits which initiates the aforementioned conversion Dozer throws the following error :
当我尝试运行启动上述转换的Junits时,推土机会引发以下错误:
org.dozer.MappingException: java.lang.NoSuchMethodException:
For Eg : I want to convert Set < Foo> to List< FOO> 例如:我想将Set <Foo>转换为List <FOO>
class Foo{
private String FOO; // this contains same data as the enum FOO
private String foo1;
}
enum FOO {
A,B;
}
It would have been better if you had shown the full stack trace, mapping xml, customer converter, and relevant codes. 如果您显示了完整的堆栈跟踪,映射xml,客户转换器和相关代码,那就更好了。 I can hazard a guess that you're getting NoSuchMethodException because you're using the enum constructor wrongly.
我可能会误以为您会收到NoSuchMethodException,因为您错误地使用了枚举构造函数。
However, here's a CustomConverter which successfully maps a Set of Objects to a List of enums (I've labelled the enum as 'Bar' instead of 'FOO'): 但是,这是一个CustomConverter,它成功地将一组对象映射到枚举列表(我将枚举标记为“ Bar”而不是“ FOO”):
public class EnumClassConverter implements CustomConverter{
public Object convert(Object dest, Object source, Class<?> arg2, Class<?> arg3) {
if (source == null)
return null;
if (source instanceof Set<?>){
Set<Foo> setOfFoos = (Set<Foo>) source;
List<Bar> listOfBars = new ArrayList<Bar>();
for (Foo f:setOfFoos){
if (f.getFOO()=="A") listOfBars.add(Bar.A);
else listOfBars.add(Bar.B);
}
return listOfBars;
}
else if (source instanceof List<?>){
List<Bar> listOfBars = (List<Bar>) source;
Set<Foo> setOfFoos = new HashSet<Foo>();
for (Bar b : listOfBars){
Foo f = new Foo();
if (b ==Bar.A){
f.setFOO("A");
}
else f.setFOO("B");
setOfFoos.add(f);
}
return setOfFoos;
}
else {
throw new MappingException("Converter EnumClassConverter "
+ "used incorrectly. Arguments passed in were:"
+ dest + " and " + source);
}
}
}
and the mapping xml: 和映射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>beans.FooContainer</class-a>
<class-b>beans.BarContainer</class-b>
<field custom-converter="converter.EnumClassConverter" >
<a>fooSet</a>
<b>listOfBars</b>
</field>
</mapping>
</mappings>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.