How do you make a deep copy of an object?

前端 未结 19 1889
执念已碎
执念已碎 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条回答
  •  梦毁少年i
    2020-11-21 23:55

    You can make a deep copy with serialization without creating files.

    Your object you wish to deep copy will need to implement serializable. If the class isn't final or can't be modified, extend the class and implement serializable.

    Convert your class to a stream of bytes:

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(object);
    oos.flush();
    oos.close();
    bos.close();
    byte[] byteData = bos.toByteArray();
    

    Restore your class from a stream of bytes:

    ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
    (Object) object = (Object) new ObjectInputStream(bais).readObject();
    

提交回复
热议问题