6

Is it possible to make a deep copy/clone of a Java object without using serialization ? If so then how ?

9
  • What are you trying to achieve? Commented Aug 24, 2014 at 13:40
  • 1
    Short of reflection (if even that), there's no way to make a deep copy of an arbitrary object, period. To use serialization the object must be serializable. Commented Aug 24, 2014 at 13:47
  • suppose i am trying to create a generic immutable collection, where i don't know if the elements implement serializable but once created you can't add, remove or even update/change an element but you can get a reference of an element using peek() (In short they become read-only from outside). So, i was thinking maybe deep clone and return the cloned object on peek() ? Commented Aug 24, 2014 at 13:57
  • It's not the responsibility of the collection to make its elements immutable. It's the responsibility of the class of the elements itself, or of the user of the collection (which could store read-only adapters of a mutable class, for example). The collection shouldn't bother with that. Commented Aug 24, 2014 at 14:04
  • 1
    You would have to put in a lot of assumptions about the objects you are copying for the concept "deep copy" to even make sense, let alone be feasible. In other words, no, there is no generic solution as you envision it. Commented Aug 24, 2014 at 14:31

1 Answer 1

5

You could use the Java Deep-Cloning Library to make deep copies of objects. It is really useful when you can't (or don't want) to make your classes serializable. The use is straight-forward:

Cloner cloner = new Cloner();

MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o
Sign up to request clarification or add additional context in comments.

3 Comments

After using this API my JVM get crashes and getting following error *** Error in `/etc/alternatives/java_sdk_1.8.0_openjdk/bin/java': double free or corruption (out): 0x00007f250c140b10 *** ======= Backtrace: ========= /lib64/libc.so.6(+0x81609)[0x7f2563519609]
What about security concerns?! Maybe I do not want my class to be Serializable because of security concerns? How does that library achieve cloning underneath, does it also use Serializable at some point?
Reading the code at the Github link, it creates a new instance of an object of the same class (using org.objenesis.instantiator.ObjectInstantiator;), and copies all the fields recursively, making some optimizations/assumptions based on collection type if applicable.

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.