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 use a library that has a simple API, and performs relatively fast cloning with reflection (should be faster than serialization methods).
Cloner cloner = new Cloner();
MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o
Apache commons offers a fast way to deep clone an object.
My_Object object2= org.apache.commons.lang.SerializationUtils.clone(object1);
A few people have mentioned using or overriding Object.clone()
. Don't do it. Object.clone()
has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone()
on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.
The schemes that rely on serialization (XML or otherwise) are kludgy.
There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. String
s) do not need to be copied. As an aside, you should favor immutability for this reason.
XStream is really useful in such instances. Here is a simple code to do cloning
private static final XStream XSTREAM = new XStream();
...
Object newObject = XSTREAM.fromXML(XSTREAM.toXML(obj));
Use XStream(http://x-stream.github.io/). You can even control which properties you can ignore through annotations or explicitly specifying the property name to XStream class. Moreover you do not need to implement clonable interface.
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 cause StackOverflowError
.
public static <T> T copy(T anObject, Class<T> classInfo) {
Gson gson = new GsonBuilder().create();
String text = gson.toJson(anObject);
T newObject = gson.fromJson(text, classInfo);
return newObject;
}
public static void main(String[] args) {
String originalObject = "hello";
String copiedObject = copy(originalObject, String.class);
}