In Java, if a Class A needs to implement deep clone, simply perform the following two points at the same time:
1. Class A must implement the serializable interface. For example:
class A implements serializable
{
...
}
2. Add the following method to Class:
Public A clone () // deep clone for object of any complexity
{
Try
{
Bytearrayoutputstream baos =NewBytearrayoutputstream ();
objectoutputstream OOS = New objectoutputstream (baos );
Oos. writeobject (This);
Oos. Close ();
bytearrayinputstream BAIS = New bytearrayinputstream (baos. tobytearray ();
objectinputstream OIS = New objectinputstream (BAIS );
Object Ob = Ois. readobject ();
Ois. Close ();
Return(A) ob;
}
Catch(Exception E)
{
E. printstacktrace ();
}
return null ;
}
This is similar to the following:Code:
A A = new ();
A B = A. Clone ();
This is to achieve deep clone using serialization.