java如何拷贝对象
深拷贝与浅拷贝的概念
浅拷贝仅复制对象的引用,不复制内部属性指向的对象;深拷贝会递归复制所有属性指向的对象,生成完全独立的副本。
实现浅拷贝的方法
1. 使用clone()方法
类需实现Cloneable接口并重写clone()方法:
class Person implements Cloneable {
String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 调用
Person p1 = new Person();
Person p2 = (Person) p1.clone();
2. 通过构造方法或工厂方法
手动复制字段值:
Person p2 = new Person();
p2.name = p1.name;
实现深拷贝的方法
1. 递归调用clone()
对引用类型属性单独调用clone():
class Address implements Cloneable {
String city;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable {
Address address;
@Override
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) this.address.clone();
return cloned;
}
}
2. 使用序列化
通过ObjectOutputStream和ObjectInputStream实现:
import java.io.*;
class DeepCopyUtil {
static <T> T deepCopy(T obj) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
}
}
// 要求所有涉及类实现Serializable接口
3. 第三方库工具
Apache Commons Lang的SerializationUtils:

Person p2 = SerializationUtils.clone(p1);
注意事项
clone()方法可能导致浅拷贝问题,需谨慎处理嵌套对象。- 序列化方式性能较低,但适合复杂对象图的深拷贝。
- 确保被拷贝对象的类及其引用类型属性均支持所用拷贝方式(如
Cloneable或Serializable)。






