在Java中实现深拷贝的方法有几种:
public class MyClass implements Cloneable {
private int value;
private MyObject obj;
public MyClass(int value, MyObject obj) {
this.value = value;
this.obj = obj;
}
@Override
protected Object clone() throws CloneNotSupportedException {
MyClass copy = (MyClass) super.clone();
copy.obj = (MyObject) obj.clone();
return copy;
}
}
import java.io.*;
public class MyClass implements Serializable {
private int value;
private MyObject obj;
public MyClass(int value, MyObject obj) {
this.value = value;
this.obj = obj;
}
public MyClass deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (MyClass) ois.readObject();
}
}
import org.apache.commons.lang3.SerializationUtils;
public class MyClass {
private int value;
private MyObject obj;
public MyClass(int value, MyObject obj) {
this.value = value;
this.obj = obj;
}
public MyClass deepCopy() {
return SerializationUtils.clone(this);
}
}
无论使用哪种方法,都需要确保所有需要拷贝的成员变量都是可序列化的或实现了Cloneable接口,并在拷贝过程中进行适当的处理。