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.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Deep-copy of Serializable objects */ public class SerializableObjectCloner{ public static Object clone(Object original) { Object clone = null; try { //Increased buffer size to speed up writing ByteArrayOutputStream bos = new ByteArrayOutputStream(5120); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(original); out.flush(); out.close(); ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); clone = in.readObject(); in.close(); bos.close(); return clone; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return null; } }
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.