Java: recommended solution for deep cloning/copying an instance

后端 未结 9 2393
半阙折子戏
半阙折子戏 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 02:02

    For deep cloning implement Serializable on every class you want to clone like this

    public static class Obj implements Serializable {
        public int a, b;
        public Obj(int a, int b) {
            this.a = a;
            this.b = b;
        }
    }
    

    And then use this function:

    public static Object deepClone(Object object) {
        try {
            ByteArrayOutputStream baOs = new ByteArrayOutputStream();
            ObjectOutputStream oOs = new ObjectOutputStream(baOs);
            oOs.writeObject(object);
            ByteArrayInputStream baIs = new ByteArrayInputStream(baOs.toByteArray());
            ObjectInputStream oIs = new ObjectInputStream(baIs);
            return oIs.readObject();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    

    like this: Obj newObject = (Obj)deepClone(oldObject);

提交回复
热议问题