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

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

 

深拷贝接口:

public static <T extends Serializable> 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();
}

 

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

 

posted @ 2020-11-06 16:56  hjjsunli  阅读(115)  评论(0编辑  收藏  举报