Serialization is an alternative and easiest way of deep cloning (with some performance overhead). Java serialization involves serializing the object into bytes and from bytes to object again.
Note, when you deep copy through serialization, you should make sure that all classes in the object's graph are serializable. Otherwise, java.io.NotSerializableException will be thrown.
It is advisable to use in-memory deep cloning whenever it is the only need and we don’t need to persist the object for future use.
1. Java deep cloning example
To demonstrate deep cloning, I have created a demo class named Employee. This has three variables i.e. firstName, lastName and addressList. I will add a deepCopy() instance level method to this class. Whenever invoked on an instance of Employee, it will return an exact clone/deep copy of that instance.
For deep cloning, we must first serialization and then deserialization. For serialization, ByteArrayOutputStream and ObjectOutputStream must be used. ByteArrayInputStream and ObjectInputStream must be used for deserialization.
2. Test the deep cloning
Let’s test the class and create a deep copy of instance to verify if it works as expected.
- When you implement the deep cloning, the copied object may contain some other object its references are copied recursively in the deep copy.
- Cyclic dependencies will be a big problem while implementing a deep copy. It does implements deep copy implicitly and gracefully handling cyclic dependencies.
- Serialization is more expensive than using object.clone().
- Please also, remember that deep cloning is evil for singleton pattern. It makes possible of having multiple instances of singleton classes.
- Not all objects are serializable (transient variable cannot be cloned).
- Serialization is not simple to implement for the deep cloned object.