'How to copy member variables of the same name from different classes. (in JAVA)

there are two classes below which are externally generated (can't be fixed by me)

public class ClassA{
 private Obj a;
 private Obj b;
 private Obj c;
 private Obj d;
}
@Builder
public class ClassB{
 private Obj a;
 private Obj b;
 private Obj c;
 private Obj d;
 private Obj e;
 private Obj f;
 ...(any other obj)
}

and I made bInstance like below.

ClassB bInstance = ClassB.builder().a(a).b(b).c(c).d(d).e(e).f(f).build();

And I want to get aInstance(ClassA) of bInstance and a,b,c,d with the same values (copying values with the same name). How can I get the value I want?



Solution 1:[1]

There are multiple ways of doing it but if you want a general, automated way, the best lib that I've worked with is MapStruct. Please check the reference documentation for examples on how to use it.

If you don't want or can't introduce a library and there are only a few situations where this copying between similar objects of different classes is necessary, you can create a class that does the work for you:

public class BeanMapper {
    public static ClassA from(ClassB b) {
        // assuming class A doesn't have a builder
        ClassA a = new ClassA();
        a.setA(b.getA());
        a.setB(b.getB());
        // set other properties...
        return a;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matheus Moreira