The cleanest cloning

Many a times we need to clone complex objects to promote re-using preset values while achieving perfect decoupling, as in, two identical objects but having different references to nested depths. The simplest and most elegant solution is serialization and de-serialization. Of course, there is a small catch here, the objects should be serializable. Moreover, there may be a slight performance glitch. This creates a deep-copy of the original object.

I am pasting the code below:

public Object createClone() throws Exception {

// serialize
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(this);
oos.close();

// de-serialize
ByteArrayInputStream inputStream = new ByteArrayInputStream(
outputStream.toByteArray());
ObjectInputStream ois = new ObjectInputStream(inputStream);

return ois.readObject();

}

One thought on “The cleanest cloning

Leave a Reply

Your email address will not be published. Required fields are marked *