今天看ECS的源代码,发现一个深度克隆的简单通用实现,当然这个实现会克隆所有的成员,因此如果你的类有一些不能保存或者克隆的成员,那么这个就无效了,但是如果你的类就是简单的POJO,那么这个还是不错的,正在为我的持久层的克隆发愁,这个应该是我正想要的。我也相信这个对很多人一样有用,虽然性能可能不是很好:
/**
Allows all Elements the ability to be cloned.
*/
public Object clone()
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(this);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bin);
Object clone = in.readObject();
in.close();
return(clone);
}
catch(ClassNotFoundException cnfe)
{
throw new InternalError(cnfe.toString());
}
catch(StreamCorruptedException sce)
{
throw new InternalError(sce.toString());
}
catch(IOException ioe)
{
throw new InternalError(ioe.toString());
}
}
发表评论