4

Let say I have class A

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

I create new Instance of A, then second Instance of A:

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

Is there any easy way (reflections or so) to copy fields from a2 to a1 without assigning Instance a2 to a1 (I don't want to change reference of Instance a1, only values of its fields)? I know I can do it manually in some method, but if there are many fields its kinda not practical.

I was thinking if there is maybe some way over reflections ?

Anyone has some experience with it ?

To Kra
  • 3,344
  • 3
  • 38
  • 45

2 Answers2

4

You can use

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

See here

StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

There are many things that you need to consider and many ways you can do this depending on the requirements. Using reflection you could to something like this

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

Note that a2 is NOT a deep copy of a1 but it has asssigned the same references of a1. That means that if your class A has a object field of class B like this

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

then after you have created a dublicate a2 , changing the myString of b object will be reflected to both a1 and a2. This happens becuase both a1 and a2 have reference to the same B instance.

C.LS
  • 1,319
  • 2
  • 17
  • 35