If the Java class implements the Serializable interface but does not have the public clone() method, you can usually create such a deep copy:
class CloneHelper { @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); T copy = (T) ois.readObject(); ois.close(); return copy; } catch (ClassNotFoundException ex) {
I often come across third-party library classes like this, and resort to hacks like the ones described above. I even extended ObjectOutputStream to make the copy smaller. This never caused serious problems other than being inefficient (slow encoding / decoding, and serialization timelines can consume a lot of memory.)
And if it is unsafe to use this technique, the class probably should not have been declared Serializable .
So, what would I like to know if your class is Serializable , which might prevent you from defining a public clone() method (using either the Cloneable interface or the copy constructor?)
Related: Copy Object in Java
java serialization serializable deep-copy
finnw
source share