使用序列化和反序列化完成对象的深拷贝

class SerialCloneable implements Cloneable, Serializable {
    @Override
    public Object clone() {
        try {
            //使用ByteArrayOutputStream 作为输出
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bout);
            //将this 对象序列化输出
            out.writeObject(this);
            out.close();

            //从输出中读入并生成clone 对象
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            ObjectInputStream in = new ObjectInputStream(bin);
            Object ret = in.readObject();
            in.close();

            //返会clone对象的引用,这是this的一个深拷贝
            return ret;
        } catch (Exception e) {
            return null;
        }
    }

  摘自Java核心技术卷二,使用序列化能非常简便的克隆对象,并且是深拷贝,只要对象继承这个SerialCloneable类 (实现了Serializable 接口)。

将对象序列化到流后再将其读回 读回后产生的对象就是原始对象的深拷贝。

但是这种做法甚至比“笨办法” --显式的从原始对象构造新对象慢很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值