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.

6
  • 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. Commented Jan 22, 2016 at 8:05
  • how can we done this if the object is not serializable Commented Jan 22, 2016 at 8: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? Commented Jan 22, 2016 at 9: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. Commented Jan 22, 2016 at 9: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. Commented Jan 22, 2016 at 9:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
MyObject object = new MyObject(<parameters of the old object>); 

If you simply use

object = oldObject; 

you will copy the reference.

1 Comment

what if there is an object reference inside. In that case the object reference will be copied.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.