`
colorlife
  • 浏览: 130446 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

使用对象序列化进行克隆

阅读更多

摘自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;
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics