在 Java 中,Clone 方法用于創建并返回一個對象的副本
public class MyClass implements Cloneable {
// ...
}
public class MyClass implements Cloneable {
private SomeOtherClass someOtherClass;
@Override
protected MyClass clone() throws CloneNotSupportedException {
MyClass cloned = (MyClass) super.clone();
cloned.someOtherClass = new SomeOtherClass(this.someOtherClass);
return cloned;
}
}
public class MyClass {
private SomeOtherClass someOtherClass;
public MyClass(MyClass other) {
this.someOtherClass = new SomeOtherClass(other.someOtherClass);
}
}
import java.io.*;
public class MyClass implements Serializable {
private SomeOtherClass someOtherClass;
public MyClass deepCopy() {
MyClass copied = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
copied = (MyClass) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return copied;
}
}
總之,實現 Clone 技巧和最佳實踐的關鍵是確保對象的深拷貝??梢愿鶕唧w需求和場景選擇合適的方法,如重寫 clone 方法、使用拷貝構造函數或 Java 序列化等。同時,要注意處理 CloneNotSupportedException,并在設計類時考慮封裝性和不變性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。