Hello. Tell me how to implement deep copying of objects in java. Thank.
2 answers
https://stackoverflow.com/a/28195274 - My_Object object2= org.apache.commons.lang.SerializationUtils.clone(object1);
https://stackoverflow.com/a/7596565 - using serialization (did not check, theoretically, should work):
If the class is final
or cannot be changed, you need to implement
the serializable
interface. Convert a 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();
Next, we resume the class object from the byte stream:
ByteArrayInputStream bais = new ByteArrayInputStream(byteData); (Object) object = (Object) new ObjectInputStream(bais).readObject();
https://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java - more answers, different libraries for this purpose.
- It would be great if you do not just link to SO, but translate the appropriate answer, saving the link. - Nofate ♦
A library for cloning is available here: https://code.google.com/p/cloning/
Deep cloning with this library comes down to two lines of code:
Cloner cloner = new Cloner(); DeepCloneable clone = cloner.deepClone(this);