Search code examples
javamappingorika

Orika mapper - Field subtype


I have the following concrete classes:

public class A1 {} 

public class B1 extends A1 {}

public class A2 {}

public class B2 extends A2 {}

public class B3 extends A2 {}

And I'd like to get a B2 instance when mapping MapperFacade.map(b1Instance, A2.class)

I need this because A2 has many subtypes (B2 and B3 as showed) and I need to map the appropriate one when needed

Is it possible to achieve this with Orika?


Solution

  • For the people that will face the same problem, I solved this creating a CustomMapper like this that verifies which is the sub-type to instantiate

    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);
    
            }
    }