Home > Software design >  Best way to copy all properties from different class under different package
Best way to copy all properties from different class under different package

Time:04-14

I have two classes, C1 & C2, inside different package.

package p1
class C1 {}

package p2
class C2 {
  C1 abc;--> refer to class C1 in package p1
  int i;
  String s
}

`-----------

package p3
class C1 {}

package p4
class C2 {
  C1 abc; --> refer to class C1 in package p3
  int i;
}

Let's assume some fields in p4.C2 class is missing but it is there in p2.C2. What is the best way to copy all values from p2.C2 to p4.C2? Fields that are missing in p4.C2 should be ignored while copying.

CodePudding user response:

I think the question is not related to Spring and it's a general Java question.

Make all your classes public so that they are accessible from outside the package. And if you want C1 class properties should available in C2 then follow the below code.

import P1.*;
class C2 extends C1
{
....
}

In this way, all the properties of class C1 will be available to class C2. You can follow same step for class C3 and C4.

CodePudding user response:

You can try using PropertyUtils

    p2.C2 source = new p2.C2();
    p4.C2 destination = new p4.C2();    
    PropertyUtils.copyProperties(destination, source);
  • Related