Orika mapper - Field子类型

时间:2017-08-01 12:56:08

标签: java mapping orika

我有以下具体课程:

public class A1 {} 

public class B1 extends A1 {}

public class A2 {}

public class B2 extends A2 {}

public class B3 extends A2 {}

我希望在映射MapperFacade.map(b1Instance, A2.class)

时获得B2实例

我需要这个,因为A2有很多子类型(如图所示的B2和B3),我需要在需要时映射适当的子类型

是否有可能通过Orika实现这一目标?

1 个答案:

答案 0 :(得分:0)

对于将面临同样问题的人,我解决了这个问题,创建了一个这样的CustomMapper来验证哪个是要实例化的子类型

mapperFactory.classMap(SOURCE.class, DEST.class)
                    .customize(new CustomMapper<SOURCE, DEST>() {
        @Override
        public void mapAtoB(SOURCE source, DEST dest, MappingContext context) {

            //verifies the type to instantiate
            private A2 a2 = isB2() ? new B2() : new B3;             
            //use the mapper for the class (will use the B2 or B3 mapper)
            mapperFacade.map(source.getA2(), a2);
            // set the field into the dest object
            dest.setB1(a2);

        }
}