java如何创建副本
创建对象副本的方法
在Java中创建对象副本可以通过多种方式实现,具体取决于对象类型和需求。
浅拷贝(Shallow Copy)
使用clone()方法实现浅拷贝,需要类实现Cloneable接口并重写clone()方法:
class MyClass implements Cloneable {
private int value;
private String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
MyClass original = new MyClass();
MyClass copy = (MyClass) original.clone();
浅拷贝只复制基本类型字段和对象引用,不复制引用指向的对象本身。
深拷贝(Deep Copy)
实现深拷贝需要手动复制所有引用对象:
class DeepCopyClass implements Cloneable {
private InnerClass inner;
@Override
protected Object clone() throws CloneNotSupportedException {
DeepCopyClass copy = (DeepCopyClass) super.clone();
copy.inner = (InnerClass) inner.clone(); // 递归克隆引用对象
return copy;
}
}
复制构造函数
通过定义接收同类对象作为参数的构造函数来创建副本:
class CopyConstructorClass {
private int data;
public CopyConstructorClass(CopyConstructorClass other) {
this.data = other.data;
}
}
CopyConstructorClass original = new CopyConstructorClass();
CopyConstructorClass copy = new CopyConstructorClass(original);
工厂方法
使用静态工厂方法创建副本:
class FactoryCopyClass {
public static FactoryCopyClass newInstance(FactoryCopyClass prototype) {
FactoryCopyClass copy = new FactoryCopyClass();
// 复制所有字段
return copy;
}
}
序列化实现深拷贝
通过序列化/反序列化实现完全的深拷贝:
import java.io.*;
public class SerializationCopy {
public static <T extends Serializable> T deepCopy(T object) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
工具类方法
使用第三方库如Apache Commons或Spring Framework提供的复制工具:

// Apache Commons BeanUtils
MyClass copy = new MyClass();
BeanUtils.copyProperties(copy, original);
// Spring BeanUtils
MyClass copy = new MyClass();
BeanUtils.copyProperties(original, copy);
选择哪种方法取决于具体需求,浅拷贝适合简单对象,深拷贝适合包含复杂引用结构的对象,工具类方法适合快速实现而无需修改原有类结构。






