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.

4
  • Without modifying which class? Commented May 31, 2013 at 16:17
  • 1
    stackoverflow.com/questions/4394978/… Commented May 31, 2013 at 16:17
  • Why would you need such a thing. Just make the class implement cloneable and clone it to make new objects. Commented May 31, 2013 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. Commented May 31, 2013 at 16:38

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
@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.
1

try this simple way

 firstObj.setElem1 (secObj.getElem1());

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.