Java: recommended solution for deep cloning/copying an instance

后端 未结 9 2239
半阙折子戏
半阙折子戏 2020-11-22 01:28

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

9条回答
  •  无人共我
    2020-11-22 01:58

    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);
    
    }
    

提交回复
热议问题