java序列化实现深拷贝代码
时间: 2023-10-26 12:43:13 浏览: 136
序列化(Serialization)实现深拷贝.md
当然可以,以下是一段 Java 序列化实现深拷贝的代码:
import java.io.*;
public class DeepCopy implements Serializable {
private int num;
private DeepCopyObject obj;
public DeepCopy(int num, DeepCopyObject obj) {
this.num = num;
this.obj = obj;
}
public DeepCopy deepCopy() {
DeepCopy copy = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
copy = (DeepCopy) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return copy;
}
}
class DeepCopyObject implements Serializable {
private String name;
public DeepCopyObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "DeepCopyObject{" +
"name='" + name + '\'' +
'}';
}
}
(笑话讲述:)
为什么 Java 程序员常常深爱自己的代码?
因为他们深拷贝了自己啊!
阅读全文