利用序列化进行深度克隆

使用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;
    }

 

posted @ 2017-05-31 09:47  九人稚。  阅读(520)  评论(0编辑  收藏  举报