Clone() method by default create's a shallow copy. For deep clone/copy you have to either override clone() method or provide a separate method.
The simplest approach to deep cloning is to use serialization, where you serialize and deserialize the object and return the deserialized version. This will be a deep copy/clone, assuming everything in the object tree is serializable.
If everything is not serializable, you'll have to implement the deep cloning behavior on your own.
Assuming everything is serializable, the following code snippet should create a complete deep copy of the current class instance:
ByteArrayOutputStream byteArrOs = new ByteArrayOutputStream();
ObjectOutputStream objOs = new ObjectOutputStream(byteArrOs);
objOs.writeObject(this);
ByteArrayInputStream byteArrIs = new ByteArrayInputStream(byteArrOs.toByteArray());
ObjectInputStream objIs = new ObjectInputStream(byteArrIs);
Object deepCopy = objIs.readObject();
0 Responses to How to do a deep clone of an object
Something to say?