您將需要手動實施A.clone()
,以便它只克隆要克隆的對象。的Object.clone
默認的實現是執行一個淺拷貝操作,所以你需要做這樣的事情:
public class A implements Cloneable {
[...]
public Object clone() {
Object obj = null;
try {
obj = super.clone();
// super.clone performs a "shallow copy" operation.
// Now you will need to manually clone any objects for
// which a "deep copy" operation is desired, e.g.
//
// obj.memberX = memberX.clone();
// obj.memberY = memberY.clone();
// ...
//
} catch (CloneNotSupportedException ex) {
// Should not happen..
}
return obj;
}
}
這是假設你知道你想克隆出哪些對象(即哪些對象在那裏建設的過程中產生)。