One way of deep copying an object graph is by using serialization-deserialization
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(topClass);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
MyClass1 copy = (MyClass1) in.readObject();
To do this all the classes must implement Serializable. The serialization mechanism ensures that if two references reference the same instance in the original, they will also reference the same (new) instance in the new one.
The drawbacks are:
- They have to implement Serializable
- They all have to be contained in one object. If two objects directly or indirectly reference the same instance, then the result of deep copying those two separately will produce two separate instances of the referred object.