This technique requires serializable objects (implement java.io.Serializable). Basically, the object is serialized (writeObject()) and deserialized (readObject()) in a new object. A helper method able to accomplish this is listed as follows:
private static <T> T cloneThroughSerialization(T t) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(t);
ByteArrayInputStream bais
= new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (T) ois.readObject();
} catch (IOException | ClassNotFoundException ex) {
// log exception
return t;
}
}
So, the object is serialized in ObjectOutputStream and deserialized in ObjectInputStream. Cloning an object via this method can be accomplished as follows:
Point point = new Point(...);
Point clone = cloneThroughSerialization(point);
A built-in solution based on serialization is provided by Apache Commons Lang, via SerializationUtils. Among its methods, this class provides a method named clone() that can be used as follows:
Point point = new Point(...);
Point clone = SerializationUtils.clone(point);