摘自java核心技术
注意:效率较低
class SerialCloneable implements Cloneable, Serializable{
public Object clone()
{
try{
//save the object to a byte array
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
//read a cline of the object from the byte array
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object ret = in.readObject();
in.close();
return ret;
}catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
本文介绍了一种通过序列化实现的深拷贝方法,该方法适用于实现了Cloneable和Serializable接口的Java类。虽然效率较低,但能确保对象的完全复制,避免了浅拷贝可能带来的副作用。
274

被折叠的 条评论
为什么被折叠?



