对象序列化为字节流,再从字节流反序列化为新的对象。
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;
}
}
标签:SelfCloneSample,Java,字节,another,byteArrayOutputStream,new,拷贝,序列化
From: https://www.cnblogs.com/cyansill/p/18392766