1

How can we copy an object in java without copying the reference. If any object is present inside then we should copy the value only with out modifying the original object reference.

How can this be done in a general way. That is we don't know whether the object is serializable or not.

I want to write a method which will deep copy the object passed to it. The object passing to it will be of any type.

vineeth sivan
  • 510
  • 3
  • 18
  • Your best option is probably to write a copy constructor yourself, and do `MyClass newObj = new MyClass(oldObj);`. Other options are to rely on serialization/deserialization or `Object.clone` but please read [Copy Constructor versus Cloning](http://www.artima.com/intv/bloch13.html). – aioobe Jan 22 '16 at 08:05
  • how can we done this if the object is not serializable – vineeth sivan Jan 22 '16 at 08:37
  • Are you controlling the implementation? (Can you modify the code of the class?) Or do you want to deep copy an object from a library? – aioobe Jan 22 '16 at 09:19
  • No, I cannot modify the class of the object. I simply want to write a general method that will copy the object passing as a parameter to it. – vineeth sivan Jan 22 '16 at 09:49
  • Not possible I'm afraid. Consider what would happen if the object you're trying to copy holds a reference to a singleton object for instance. – aioobe Jan 22 '16 at 09:53
  • That's make sense. Thank you for your help. Appreciated – vineeth sivan Jan 22 '16 at 10:54

2 Answers2

1

Try SerializationUtils.clone() from Apache Commons Lang. If you don't want to include the entire library, copy that method into your code. The object has to be serializable.

Oliv
  • 10,221
  • 3
  • 55
  • 76
0
MyObject object = new MyObject(<parameters of the old object>);

If you simply use

object = oldObject;

you will copy the reference.

aioobe
  • 413,195
  • 112
  • 811
  • 826
LordAnomander
  • 1,103
  • 6
  • 16