将转换器与嵌套对象一起使用时出现问题

时间:2019-07-09 10:37:14

标签: java modelmapper

我有以下代码和要映射的相关对象层次结构(A,B-> ADTO,BDTO)。特别是,我只想将转换器使用特定属性(day-> dayStrtype-> typeStr)将Enum字段映射到String:

public class Test {

    @Data
    @NoArgsConstructor
    static class A {

        enum Day {
            MON, TUE, WED, THU, FRI, SAT, SUN
        }

        private Day day;

        private B b;
    }

    @Data
    @NoArgsConstructor
    static class B {

        enum Type {
            A, B, C
        }

        private Type type;

        private int value;
    }

    @Data
    @NoArgsConstructor
    static class ADTO {

        private String dayStr;

        private BDTO b;
    }

    @Data
    @NoArgsConstructor
    static class BDTO {

        private String typeStr;

        private int value;
    }

    public static void main(String[] args) {

        A a = new A();
        B b = new B();
        b.setType(B.Type.A);
        b.setValue(34);
        a.setDay(A.Day.FRI);
        a.setB(b);

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        Converter<Enum, String> enumStringConverter = new AbstractConverter<Enum, String>() {
            @Override
            protected String convert(Enum source) {
                if (source != null) {
                    return source.name();
                } else {
                    return null;
                }
            }
        };

        TypeMap<A, ADTO> typeMap = modelMapper.createTypeMap(A.class, ADTO.class);
        typeMap.addMappings(m -> m.using(enumStringConverter).map(A::getDay, ADTO::setDayStr));
        TypeMap<B, BDTO> typeMap2 = modelMapper.createTypeMap(B.class, BDTO.class);
        typeMap2.addMappings(m -> m.using(enumStringConverter).map(B::getType, BDTO::setTypeStr));
        System.out.println(modelMapper.map(a, ADTO.class));
        modelMapper.validate();
    }
}

这是输出:

Test.ADTO(dayStr=FRI, b=Test.BDTO(typeStr=null, value=34))

Exception in thread "main" org.modelmapper.ValidationException: ModelMapper validation errors:

1) Unmapped destination properties found in TypeMap[A -> ADTO]:

    com.voxloud.subscription.kafka.builder.Test$BDTO.setTypeStr()

1 error
    at org.modelmapper.internal.Errors.throwValidationExceptionIfErrorsExist(Errors.java:246)
    at org.modelmapper.ModelMapper.validate(ModelMapper.java:547)
    at com.voxloud.subscription.kafka.builder.Test.main(Test.java:84)

typeMap2似乎被忽略了,因此typeStr为null且未映射。难道我做错了什么?我想念什么?感谢您的帮助!

0 个答案:

没有答案