Deep cloning of Serializable objects

The following code snippet shows how to use Object I/O streams to deep clone Serializable objects. The object bytes once written on an ObjectOutputStream can be read back to a new object with all the populated values intact. The only catch is that, because the object is written and then read from a stream, this process is slower then the normal getter-setter approach.

1 Comment

This is exactly the approach I have taken :). I wanted a general utility to deep clone an entire object (graph) based at a business entity object. I took the easy approach of using apache.commons.lang's SerializationUtils; the code becomes:@SuppressWarnings("unchecked") public static T deepClone(T object) { return (T) deserialize(serialize(object)); }Unfortunately as you pointed out this is very slow.

Leave a Reply