序列化机制为对象克隆提供了便捷方式,只要对应的类序列化即可。序列化克隆是深度克隆。
class SerialCloneable implementsCloneable, Serializable{
public Object clone(){
try{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object object = in.readObject();
in.close();
return object;
}catch(Exception e){
return null;
}
}
}