Java 运用字节流实现的针对对象的深拷贝

cyansill / 2024-09-02 / 原文

对象序列化为字节流,再从字节流反序列化为新的对象。

class SelfCloneSample implements Serializable {
    public SelfCloneSample deepClone() {
        // 万物归于字节流,对对象序列化后再反序列化,即可实现深拷贝
        SelfCloneSample another = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);

            byte[] bytes = byteArrayOutputStream.toByteArray();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

            another = (SelfCloneSample) objectInputStream.readObject();
        } catch (Exception e) {
            System.out.println(e);
        }
        return another;
    }
}