在Java中,假定由一个类A,要实现深Clone,只需简单地同时做到下面两点即可:
1. A类要实现Serializable接口。例如:
class A implements Serializable
{
...
}
2. 在A类中加入下面的方法:
public A Clone() // Deep clone for object of any complexity
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object ob = ois.readObject();
ois.close();
return (A)ob;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
使用的时候用类似下面这样代码:
A a = new A();
A b = a.Clone();
这就是用序列化的方式来实现deep clone。
本文介绍了一种在Java中实现复杂对象深克隆的方法。通过序列化的方式,具体步骤包括让类实现Serializable接口,并在类中定义Clone方法来完成对象的复制。这种方式能够确保对象及其引用的对象都能被完整复制。
171万+

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



