Technical blog

July 11, 2008

The cleanest cloning

Filed under: java — Tags: — paawak @ 11:37

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();

}

1 Comment »

  1. Succinct.

    Comment by /\/ikolaj — May 27, 2009 @ 15:50

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress