Search code examples
javadozer

Convert a class to another with similar parameters (Every param has a mapping)


I have a class A like:

A {
  ClassB b;
  String a;
}

Now there is another class X like:

X {
  ClassY y;
  String a;
}

Now, ClassY is same as ClassB, like:

ClassB/ClassY {
  String b;
}

I want to copy an instance of A into a new object of Y.

I came across Dozer which does similar mapping but that was if the values are primitive. I couldn't understand how to map the classes in them. Trying to do this in java.

I came across the answer https://stackoverflow.com/a/36196948/2733350 but I could not find MapperFactory in Dozer.


Solution

  • You can user MapStruct. It deals pretty okay with complex objects.

    To follow your example, I have created a mapper that you can adjust accordingly (@Data comes from lombok):

    @Data
    public class A {
    
        private B b;
        private String a;
    }
    
    @Data
    public class B {
        private String b;
    }
    
    @Data
    public class Y {
    
        private String b;
    }
    

    And now you can define your actual mapper:

    @Mapper
    public interface AMapper {
    
        AMapper INSTANCE = Mappers.getMapper(AMapper.class);
    
        @Mapping(source = "b.b", target = "b")
        Y aToY(A a);
    }
    

    A small unit test:

    @Test
    public void shouldMapAToY() {
        A a = new A();
        a.setA("a variable");
        final B b = new B();
        b.setB("stuff from class b");
        a.setB(b);
    
        Y y = AMapper.INSTANCE.aToY(a);
        assertThat(y).isNotNull();
        assertThat(y.getB()).isEqualTo(b.getB());
    }