使用jdk自动的clone进行克隆只能对类中的基本数据类型进克隆,而对引用的对象无法clone,仍然是进行内存地址的拷贝

可以使用序列化的方式进行深度克隆,测试有效,但是必须要实现 Serializable 接口

/**
     * 深度克隆类
     * @return
     */
    public Object deepClone() {
        Object o = null;
        try {
            if (this != null) {
                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);
                o = ois.readObject();
                ois.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }

 

相关文章:

  • 2021-12-17
  • 2022-12-23
  • 2021-10-30
  • 2021-11-17
  • 2022-01-26
  • 2021-11-27
  • 2021-12-01
  • 2022-12-23
猜你喜欢
  • 2021-12-16
  • 2021-08-10
  • 2021-05-14
  • 2018-12-10
  • 2022-12-23
  • 2022-01-12
  • 2021-04-02
相关资源
相似解决方案