It\'s a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?
You can make a deep copy with serialization without creating files.
Your object you wish to deep copy will need to implement serializable
. If the class isn't final or can't be modified, extend the class and implement serializable.
Convert your class to a stream of bytes:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();
Restore your class from a stream of bytes:
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
(Object) object = (Object) new ObjectInputStream(bais).readObject();