Javaでオブジェクトを深くクローンする方法
Javaでオブジェクトのディープクローンを実現するには、以下の方法の1つを使用できます。
Cloneableインタフェースを実装してclone( )メソッドをオーバーライドする:
public class MyClass implements Cloneable {
private int myInt;
private String myString;
public Object clone() throws CloneNotSupportedException {
MyClass cloned = (MyClass) super.clone();
// 对于引用类型的成员变量,需要进行深度克隆
// 例如:cloned.myObject = this.myObject.clone();
return cloned;
}
}
クローンを作成するには、clone()メソッドを呼び出します。
MyClass original = new MyClass();
MyClass cloned = (MyClass) original.clone();
シリアライズ(シリアル化)とデシリアライズ(デシリアル化)を利用する
import java.io.*;
public class MyClass implements Serializable {
private int myInt;
private String myString;
public MyClass deepClone() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MyClass) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
次に、deepClone()メソッドを使用してディープクローンを作成します。
MyClass original = new MyClass();
MyClass cloned = original.deepClone();
いずれの方法を選択する場合でも、cloneされるクラスとそのすべての参照型メンバ変数は、シリアル化可能であるか、もしくはCloneableインターフェースを実装している必要があります。