Is it possible to deep copy an Object
out of the box? i.e. any other way than coding a clone
function manually.
-
Take a look at http://code.google.com/p/cloning/ – KV Prajapati Oct 20 '12 at 07:12
-
Thanks. This lib is doing the trick. but I am not looking for a lib. I'm looking for Logic. i.g. How this lib is doing this? – MBZ Oct 20 '12 at 07:32
-
That's correct. But I checked the code. It contains very little comment. It is possible to _study_ the code though but someone may describe the logic much faster and better. btw, I will keep studying the code as the last option. Thanks. – MBZ Oct 20 '12 at 07:39
-
Here is a [SO thread](http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java) that suggets - serialization/deseralization. – KV Prajapati Oct 20 '12 at 07:42
3 Answers
Cloning does not necessarily perform a deep copy. In fact, the default implementation of
Object.clone()
creates a shallow copy.If the object's closure consists of objects that implement
Serializable
orExternalizable
, you can useObjectOutputStream
andObjectInputStream
to create a deep copy ... but it is expensive.The
cloning
library is another option, but my initial reading of the code is that it relies on the class of every object in the graph providing a no-argument constructor. Then it will then patch the resulting object to have a copy of the original object's state. This process might have undesirable side-effects, depending on what the no-args constructor actually does.
In short, I don't think there is a universal solution.

- 698,415
- 94
- 811
- 1,216
-
There can't be really _universal_ solution, since it that would require cloning open files and network connections, running threads including waits, and stuff like that. – hyde Oct 20 '12 at 08:01
-
@hyde - yea, but even including the types where copying is theoretically impossible, there is still a set of types that could be copyable but aren't. – Stephen C Oct 20 '12 at 09:45
I suggest to use java.lang.reflect.
java.lang.Class expose all fields and allows reading public fields and calling public methods.
Only the private field without accessors can't be cloned.

- 14,617
- 9
- 61
- 84
I briefly looked at the cloning
library code. It does what Serialization does that is get the graph of the object internal and instead of writing to file, it writes to a memory location = which is the clone of the object. So although its faster than Serialization, its certainly doing the same thing.

- 25,375
- 5
- 50
- 78
-
Not exactly. Object deserialization creates the new objects using a JVM backdoor that creates an object without running its constructor. (The default `Object.clone()` method does something similar ...) – Stephen C Oct 20 '12 at 08:01