java如何创建深拷贝
创建深拷贝的方法
在Java中创建深拷贝需要确保对象及其所有嵌套对象都被完全复制,而不是仅复制引用。以下是几种常见方法:
实现Cloneable接口并重写clone方法
通过实现Cloneable接口并重写clone()方法,可以手动实现深拷贝。需要递归调用嵌套对象的clone()方法。
class Person implements Cloneable {
private String name;
private Address address;
@Override
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) address.clone(); // 递归调用
return cloned;
}
}
class Address implements Cloneable {
private String city;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
使用序列化与反序列化
通过将对象序列化为字节流再反序列化,可以实现完全的深拷贝。需要确保所有相关类都实现Serializable接口。
import java.io.*;
public class DeepCopyUtil {
public static <T extends Serializable> T deepCopy(T object) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(object);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (T) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Deep copy failed", e);
}
}
}
使用第三方库
Apache Commons Lang库的SerializationUtils提供了简单的深拷贝方法:
import org.apache.commons.lang3.SerializationUtils;
Person original = new Person();
Person copied = SerializationUtils.clone(original);
手动复制构造函数
为每个类创建复制构造函数,显式地复制所有字段:

class Person {
private String name;
private Address address;
public Person(Person other) {
this.name = other.name;
this.address = new Address(other.address); // 调用嵌套对象的复制构造函数
}
}
class Address {
private String city;
public Address(Address other) {
this.city = other.city;
}
}
注意事项
- 使用
Cloneable接口需要谨慎处理所有嵌套对象的复制 - 序列化方法性能较低,但适用于复杂对象图
- 第三方库简化了实现,但增加了项目依赖
- 复制构造函数提供了最明确的可控性,但需要为每个类单独实现






