I\'m wondering if there is a recommended way of doing deep clone/copy of instance in java.
I have 3 solutions in mind, but I can have miss some, and I\'d like to ha
For complicated objects and when performance is not significant i use 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 ObjectType Copy(ObjectType AnObject, Class ClassInfo)
{
Gson gson = new GsonBuilder().create();
String text = gson.toJson(AnObject);
ObjectType newObject = gson.fromJson(text, ClassInfo);
return newObject;
}
public static void main(String[] args)
{
MyObject anObject ...
MyObject copyObject = Copy(o, MyObject.class);
}