java 如何深拷贝
深拷贝的实现方法
在Java中实现深拷贝可以通过以下几种方式,确保对象及其引用的所有对象都被复制,而不仅仅是引用。
实现Cloneable接口并重写clone方法
通过实现Cloneable接口并重写clone方法,可以手动实现深拷贝。需要在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(); // 递归调用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 bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Deep copy failed", e);
}
}
}
使用第三方库
一些第三方库(如Apache Commons Lang或Gson)提供了深拷贝的工具方法。
Apache Commons Lang:
Person copiedPerson = SerializationUtils.clone(originalPerson);
Gson:
Gson gson = new Gson();
Person copiedPerson = gson.fromJson(gson.toJson(originalPerson), Person.class);
手动复制
对于简单对象,可以手动创建新对象并复制所有字段,包括引用对象的字段。

Person copiedPerson = new Person();
copiedPerson.setName(originalPerson.getName());
copiedPerson.setAddress(new Address(originalPerson.getAddress().getCity()));
注意事项
- 使用
Cloneable接口时,需要确保所有嵌套对象都支持深拷贝。 - 序列化方式性能较低,但适用于复杂对象图。
- 第三方库通常更简洁,但需引入额外依赖。
- 手动复制适用于简单场景,但维护成本较高。






