In java 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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can do a serialization-based deep clone using
org.apache.commons.lang3.SerializationUtils.clone(T)
in Apache Commons Lang, but be careful—the performance is abysmal.In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.
XStream is really useful in such instances. Here is a simple code to do cloning
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:
Restore your class from a stream of bytes:
One way to implement deep copy is to add copy constructors to each associated class. A copy constructor takes an instance of 'this' as its single argument and copies all the values from it. Quite some work, but pretty straightforward and safe.
EDIT: note that you don't need to use accessor methods to read fields. You can access all fields directly because the source instance is always of the same type as the instance with the copy constructor. Obvious but might be overlooked.
Example:
Edit: Note that when using copy constructors you need to know the runtime type of the object you are copying. With the above approach you cannot easily copy a mixed list (you might be able to do it with some reflection code).
For complicated objects and when performance is not significant i use a json library, like gson to serialize the object to json text, then deserialize the text to get new object.
gson which based on reflection will works in most cases, except that
transient
fields will not be copied and objects with circular reference with causeStackOverflowError
.You can use a library that has a simple API, and performs relatively fast cloning with reflection (should be faster than serialization methods).