How do you make a deep copy of an object?

前端 未结 19 1849
执念已碎
执念已碎 2020-11-21 23:09

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?

19条回答
  •  鱼传尺愫
    2020-11-22 00:06

    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 copy(T anObject, Class 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);
    }
    

提交回复
热议问题