class SerialCloneable implements Cloneable, Serializable {
@Override
public Object clone() {
try {
//使用ByteArrayOutputStream 作为输出
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
//将this 对象序列化输出
out.writeObject(this);
out.close();
//从输出中读入并生成clone 对象
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object ret = in.readObject();
in.close();
//返会clone对象的引用,这是this的一个深拷贝
return ret;
} catch (Exception e) {
return null;
}
}
摘自Java核心技术卷二,使用序列化能非常简便的克隆对象,并且是深拷贝,只要对象继承这个SerialCloneable类 (实现了Serializable 接口)。
将对象序列化到流后再将其读回 读回后产生的对象就是原始对象的深拷贝。
但是这种做法甚至比“笨办法” --显式的从原始对象构造新对象慢很多