java 如何拷贝对象
深拷贝与浅拷贝的区别
浅拷贝仅复制对象的引用而非对象本身,拷贝后的对象与原对象共享部分数据。深拷贝会创建一个全新的对象,包括所有嵌套对象,与原对象完全独立。
实现浅拷贝的方法
使用clone()方法需要类实现Cloneable接口并重写clone()方法:
class MyClass implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
通过拷贝构造函数实现:
class MyClass {
private int value;
public MyClass(MyClass other) {
this.value = other.value;
}
}
实现深拷贝的方法
手动实现深拷贝需要递归复制所有嵌套对象:
class DeepCopyClass implements Cloneable {
private NestedObject nested;
@Override
protected Object clone() throws CloneNotSupportedException {
DeepCopyClass copy = (DeepCopyClass) super.clone();
copy.nested = (NestedObject) nested.clone();
return copy;
}
}
使用序列化实现深拷贝:
import java.io.*;
public class SerializationUtils {
public static <T extends Serializable> T deepCopy(T object) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
oos.flush();
try (ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()))) {
return (T) ois.readObject();
}
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
第三方库解决方案
Apache Commons Lang提供的工具类:

MyClass copy = SerializationUtils.clone(original);
注意事项
实现Cloneable接口时应注意浅拷贝可能带来的副作用。使用序列化方式要求所有涉及的对象都必须实现Serializable接口。对于复杂对象图,建议使用专门的深拷贝工具或手动实现完全复制逻辑。






