Thursday, June 10, 2010

Deep Clone a object in Java

Below is the simple program to deep clone a object in java


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 *
 * @author shailesh.chandra
 *
 */
public class DeepCloneExample implements Cloneable, Serializable {

/**
*
*/
private static final long serialVersionUID = 6514927441919765349L;

public static void main(String[] args) throws CloneNotSupportedException {
DeepCloneExample deepCloneExample = new DeepCloneExample();
System.out.println(deepCloneExample);
DeepCloneExample cloneObject = (DeepCloneExample) deepCloneExample.clone();
System.out.println(cloneObject);
}

@Override
protected Object clone() throws CloneNotSupportedException {

Object object = deepClone();
return object;

}

/**
*
* @return
* @throws CloneNotSupportedException
*/
protected Object deepClone() throws CloneNotSupportedException {
DeepCloneExample clone;
try {
clone = null;
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(100);
ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream);
objectoutputstream.writeObject(this);
byte abyte0[] = bytearrayoutputstream.toByteArray();
objectoutputstream.close();
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0);
ObjectInputStream objectinputstream = new ObjectInputStream(bytearrayinputstream);
clone = (DeepCloneExample) objectinputstream.readObject();
objectinputstream.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new CloneNotSupportedException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new CloneNotSupportedException(e.getMessage());
}
return clone;

}
}

No comments: