简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM