推土机从Set <object>映射到List <enum>

时间:2016-04-11 20:12:27

标签: java dozer

我想将一组对象映射到枚举列表。我已经创建了一个自定义转换器来将枚举转换为它们的字符串等价物。当我尝试运行启动上述转换的Junits时,Dozer会抛出以下错误:

org.dozer.MappingException: java.lang.NoSuchMethodException: 

对于Eg:我想转换Set&lt; FOO&GT;列出&lt; FOO&GT;

class Foo{
    private String FOO; // this contains same data as the enum FOO
    private String foo1;
}

enum FOO { 
    A,B; 
}

1 个答案:

答案 0 :(得分:1)

如果您显示完整的堆栈跟踪,映射xml,客户转换器和相关代码,那会更好。 我可能会猜到你正在获取NoSuchMethodException,因为你错误地使用了枚举构造函数。

然而,这是一个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);
            }
    }

}

和映射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>