java实现深拷贝方式
时间: 2025-02-08 14:59:10 浏览: 65
### Java 中实现深拷贝的方法
#### 使用序列化实现深拷贝
通过将对象序列化为字节流再反序列化回来可以创建该对象的一个独立副本,这种方式适用于复杂对象图的复制。此过程能够确保新对象与其原型之间没有任何共享引用[^2]。
```java
public class DeepCopyUtil implements Serializable {
public static <T extends Serializable> T deepCopy(T object) throws IOException, ClassNotFoundException {
// 将对象序列化到ByteArrayOutputStream中
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(object);
// 反序列化回原类型的新实例
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis)) {
@SuppressWarnings("unchecked")
T copy = (T) in.readObject();
return copy;
}
}
}
}
```
值得注意的是,在上述过程中 `static` 和 `transient` 字段不会参与序列化操作。对于基本数据类型的成员变量以及不可变类(如 String),它们会被正常处理;而对于可变类,则需特别注意其内部状态的一致性和线程安全性问题。
#### 实现 Cloneable 接口并重写 clone 方法
另一种常见的做法是在目标类声明时继承自 `Cloneable` 并覆盖默认的 `clone()` 函数来提供更精细控制下的克隆行为。为了达到真正的深层复制效果,还需要针对每一个非基础类型的属性手动调用各自的 `clone()` 或者采取其他适当措施完成子组件级别的复制工作[^5]。
```java
class Person implements Cloneable {
private String name;
private int age;
private Content content;
// 构造函数、getter/setter 省略...
@Override
protected Object clone() throws CloneNotSupportedException {
Person clonedPerson = (Person) super.clone();
// 对于复合对象执行深度复制
if (this.content != null) {
clonedPerson.setContent((Content)this.content.clone()); // 假设 Content 类也实现了 Cloneable
}
return clonedPerson;
}
}
// 测试代码片段
try {
Person original = new Person("我", 13, new Content("我"));
Person copied = (Person)original.clone();
System.out.println(original.getContent().getContentValue()); // 输出 "我"
((Content)copied.getContent()).setContentValue("你");
System.out.println(copied.getContent().getContentValue()); // 修改后的输出 "你"
System.out.println(original.getContent().getContentValue()); // 不受影响仍为 "我"
} catch(CloneNotSupportedException e){
throw new AssertionError(e); // 此处理论上不应该发生异常
}
```
在这个例子中可以看到,即使原始对象的内容发生了变化,经过深拷贝得到的对象仍然保持着最初的状态不受影响。
阅读全文
相关推荐


















