1

I have an object A that contains for example:

class A{
    String elem1;
    Int elem2;
    ...get and set 
}

and i have a class B that contains same element and name of field:

class B{
    String elem1;
    Int elem2;
    ...get and set 
}

i want copy class A value into class B value without modify the class. How can solve? thanks.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Doom
  • 1,258
  • 3
  • 15
  • 24
  • Without modifying which class? – mre May 31 '13 at 16:17
  • 1
    http://stackoverflow.com/questions/4394978/copy-fields-between-similar-classes-in-java – Joe F May 31 '13 at 16:17
  • Why would you need such a thing. Just make the class implement cloneable and clone it to make new objects. – Aniket Thakur May 31 '13 at 16:22
  • @AniketThakur I believe the OP wants to create an instance of a different class, with the same properties. In this case cloning the object isn't the best solution. – Laf May 31 '13 at 16:38

4 Answers4

4

There's no "clean" way to do this; you will need to manually copy every entry.

A a = ...;
B copy = new B();
copy.elem1 = a.elem1;
copy.elem2 = a.elem2;

Alternatively, you could use reflection, but it's performance costly and somewhat unclear, and will fail if there is any inconsistencies between the classes' field definitions.

A a = ...;
B copy = new B();
for (Field field : a.getClass().getDeclaredFields()) {
    Field copyField = copy.getClass().getDeclaredField(field.getName());
    field.setAccessible(true);
    copyField.setAccessible(true);
    if (!field.getType().isPrimitive()) {
        Object value = field.get(a);
        field.set(copy, value);
    } else if (field.getType().equals(int.class)) {
        int value = field.getInt(a);
        field.setInt(copy, value);
    } else if { ... } // and so forth
}
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • copy.elem1 = a.elem1; Seriously? Variables in most cases are private(it's a good programming practice) and you must use getters/setters. And again is reflection answer to everything? – Aniket Thakur May 31 '13 at 16:27
  • 1
    getters and setters are only provided for publicly available information. If you are doing a true copy then you probably want the non-public information also. Reflection the answer for everything - no, but it is the right answer here. – rancidfishbreath May 31 '13 at 16:29
  • @AniketThakur In the question, the classes do not have getters or setters. It would be simple to modify those two lines of code to use getters and setters anyway. – FThompson May 31 '13 at 16:31
1

try this simple way

 firstObj.setElem1 (secObj.getElem1());
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

You can create a third class which would act as a factory, with a method taking an instance of A as a parameter, and returning an instance of B.

public final class MyFactory
    {
    public static B createBFromA (A instance)
        {
        B newInstance = new B ();
        newInstance.setXXX (instance.getXXX ());
        return newInstance;
        }
    }

The advantage of using an external factory is to isolate the code that creates your B instances from the rest of your code.

Laf
  • 7,965
  • 4
  • 37
  • 52
1

Better late than never but here is the answer I have found. You can use GSON to serialize the Object to String and then deserialize to the class B. Here is the tested example:

package JSON.test.obj_copy;
public class TestClassA {

    private String field1 = "pikachu";
    private Integer field2 = 1;
    private List<String> field3 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
    private Obj field4 = new Obj();

    @Override
    public String toString(){
        return new StringBuilder("field1: " + field1 + "\n")
                .append("field2: " + field2 + "\n")
                .append("field3: " + field3 + "\n")
                .append("field4: " + field4)
                .toString();
    }
}

public class TestClassB {

    private String field1;
    private Integer field2;
    private List<String> field3;
    private Obj field4;

    @Override
    public String toString(){
        return new StringBuilder("field1: " + field1 + "\n")
                .append("field2: " + field2 + "\n")
                .append("field3: " + field3 + "\n")
                .append("field4: " + field4)
                .toString();
    }
}

public class Obj {
}

public class MainObjCopy {

    public static void main(String[] args){

        TestClassA a = new TestClassA();
        TestClassB b;
        Gson g = new Gson();
        String s1 = g.toJson(a);
        b = g.fromJson(s1, TestClassB.class);

        System.out.println(b);
    }
}

Output:

field1: pikachu
field2: 1
field3: [A, B, C]
field4: JSON.test.obj_copy.Obj@22d8cfe0
Manish Kumar Sharma
  • 12,982
  • 9
  • 58
  • 105