Is it possible to make a deep copy/clone of a Java object without using serialization ? If so then how ?
To achieve a deep copy, we can serialize an object and then deserialize it to a new object.
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With