Orika - Determining constructor call without registering an ObjectFactory

2.2k views Asked by At

I need to map two classes with Orika, OrikaA and OrikaB. OrikaB class have a constructor with one parameter that doesn't exist in OrikaA class. To map OrikaA to OrikaB I used a custom ObjectFactory:

public class OrikaA {
    String fieldA;

    public OrikaA(String fieldA) {
        this.fieldA = fieldA;
    }

    public String getFieldA() {
        return fieldA;
    }
}

public class OrikaB {
    String fieldA;
    String fieldB;

    public OrikaB(String fieldA, String fieldB) {
        this.fieldA = fieldA;
        this.fieldB = fieldB;
    }

    public String getFieldA() {
        return fieldA;
    }

    public String getFieldB() {
        return fieldB;
    }
}

@Test
public void orikaObjectFactoryTest() {
    mapperFactory = new DefaultMapperFactory.Builder().build();
    mapperFactory.classMap(OrikaA.class, OrikaB.class).register();

    Type<OrikaA> orikaAType = TypeFactory.valueOf(OrikaA.class);
    Type<OrikaB> orikaBType = TypeFactory.valueOf(OrikaB.class);

    ObjectFactory<OrikaA> objectFactoryOrikaA = (Object o, MappingContext mappingContext) -> {
        OrikaB source = (OrikaB) o;
        return new OrikaA(source.getFieldA());
    };

    ObjectFactory<OrikaB> objectFactoryOrikaB = (Object o, MappingContext mappingContext) -> {
        OrikaA source = (OrikaA) o;
        return new OrikaB(source.getFieldA(), null);
    };

    mapperFactory.registerObjectFactory(objectFactoryOrikaA, orikaAType, orikaBType);
    mapperFactory.registerObjectFactory(objectFactoryOrikaB, orikaBType, orikaAType);

    MapperFacade mapper = mapperFactory.getMapperFacade();

    OrikaA orikaA = new OrikaA("text");
    OrikaB orikaB = mapper.map(orikaA, OrikaB.class);

    assertEquals(orikaA.getFieldA(), orikaB.getFieldA());
    assertNull(orikaB.getFieldB());
}

Is there another way to accomplish the same task without using the custom ObjectFactory?

0

There are 0 answers