深拷贝与浅拷贝以及深拷贝实现方法


类对象实现Serializable接口,并且生成serialVersionUID,实现clone工具类

深拷贝接口:

public static T clone(T obj) throws Exception {
  ByteArrayOutputStream bout = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(bout);
  oos.writeObject(obj);

  ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
  ObjectInputStream ois = new ObjectInputStream(bin);
  return (T) ois.readObject();
}

在业务实现过程中,需要深拷贝直接调用此拷贝接口即可。