java深度克隆对象怎么实现
Javaでオブジェクトのディープクローンを実現する方法:
- 使用序列化和反序列化:将对象先序列化为字节流,然后再将字节流反序列化为新的对象,即可完成深度克隆。这种方式需要确保对象及其所有引用的类都实现了Serializable接口。
import java.io.*;
public class DeepClone implements Serializable {
public Object clone() {
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 ois.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
- 使用Cloneable接口和clone()方法:如果对象的所有引用类型都是可变的,可以使用Cloneable接口和clone()方法来实现深度克隆。
public class DeepClone implements Cloneable {
private int value;
private ReferenceType reference;
public DeepClone(int value, ReferenceType reference) {
this.value = value;
this.reference = reference;
}
public Object clone() throws CloneNotSupportedException {
DeepClone cloned = (DeepClone) super.clone();
cloned.reference = (ReferenceType) reference.clone();
return cloned;
}
}
- サードパーティーライブラリの利用:Apache Commons Lang の SerializationUtils クラスのようなサードパーティーライブラリを使用し、clone() メソッドでディープクローンを実施する。
import org.apache.commons.lang3.SerializationUtils;
public class DeepClone {
private int value;
private ReferenceType reference;
public DeepClone(int value, ReferenceType reference) {
this.value = value;
this.reference = reference;
}
public DeepClone clone() {
return SerializationUtils.clone(this);
}
}
いずれの手法を使う場合でも、クローン対象と関連するクラスがCloneableインタフェースあるいはSerializableインタフェースの実装を行い、参照先のクラスも正しくクローンが行われる必要があります。