在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接口,并在拷貝過程中進行適當的處理。