Is it possible to make a deep copy/clone of a Java object without using serialization ? If so then how ?
-
What are you trying to achieve?Kayaman– Kayaman2014-08-24 13:40:05 +00:00Commented Aug 24, 2014 at 13:40
-
1Short 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.Hot Licks– Hot Licks2014-08-24 13:47:48 +00:00Commented 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() ?adn.911– adn.9112014-08-24 13:57:42 +00:00Commented 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.JB Nizet– JB Nizet2014-08-24 14:04:10 +00:00Commented Aug 24, 2014 at 14:04
-
1You 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.Marko Topolnik– Marko Topolnik2014-08-24 14:31:03 +00:00Commented Aug 24, 2014 at 14:31
|
Show 4 more comments
1 Answer
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
3 Comments
acg
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]
atkuzmanov
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?ryanwebjackson
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.