JAVA How to change instance field values ​​without copying a link to a new instance

Let's say I have class A

public class A {
    private int field1;
    private String field2;
    ...
}

I create a new instance of A, then a second instance of A:

A a1 = new A();
A a2 = new A();

Is there any simple way (reflection or so) for copying fields from a2to a1without assigning an instance a2to a1(I don't want to change the instance link a1, only the values ​​of its fields)? I know that I can do it manually in some method, but if there are many fields, then this is not practical.

I thought, is there any way to reflect?

Does anyone have experience?

+4
source share
2 answers

, , . , -

    A a1  //the original a
    A a2 = new A();  //the "duplicate"

    Field[] fields = A.class.getDeclaredFields();
    for (Field f : fields){
        f.setAccessible(true); //need that if the fields are not 
        //accesible i.e private fields
        f.get(a1);
        f.set(a2, f.get(a1));
    }

, a2 a1, a1. , A B,

    class A { 
          B b;
    }
    class B { 
        public String myString;
    }

dublicate a2 myString b a1, a2. , a1, a2 B.

+1

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

+4

All Articles