在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。