Possible Duplicate:
Java: recommended solution for deep cloning/copying an instance
I have an object which has to be cloned. However while cloning it should also clone the objects inside it. How is this possible ??
Possible Duplicate:
Java: recommended solution for deep cloning/copying an instance
I have an object which has to be cloned. However while cloning it should also clone the objects inside it. How is this possible ??
You must be aware that this is not a well-defined problem and deep-copying cannot be properly done in a mechanized, fully automatic way. These are some of the options:
clone
protocol, but it's considered deprecated for most scenarios nowadays;Java Deep-Cloning library The cloning library is a small, open source java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects.
Cloner cloner = new Cloner();
MyClass clone = cloner.deepClone(o);
So and here is example cloning.
You need to override clone()
method as such
public class Person implements Cloneable{
private Long id;
private Address address
@Override
protected Object clone() throws CloneNotSupportedException {
//do deep cloning
}
}
Also See
The simplest way to implement a deep copy is to serialize and then deserialize the object. Look up ObjectInputStream
and ObjectOutputStream
.
The simplest approach to deep cloning is to use Java serialization
, where you serialize
and deserialize
the object and return the deserialized version.
Another way of cloning is to provide a copy constructor to construct a new instance based on the data of the provided instance:
public MyClass(MyClass instanceToCopy)
{
...
}