clone方法的实现

public static <T> T cloneTo(T src) throws RuntimeException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            T dst = null;
             try {
                  oos = new ObjectOutputStream(baos);
                  oos.writeObject(src);
                  oos.flush();
                  ois = new ObjectInputStream(new ByteArrayInputStream(baos
                              .toByteArray()));
                   dst = (T) ois.readObject();
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {
                   if (oos != null) {
                         try {
                              oos.close();
                        } catch (IOException e) {
                               throw new RuntimeException();
                        }
                  }
                  oos = null;
                   if (ois != null) {
                         try {
                              ois.close();
                        } catch (IOException e) {
                               throw new RuntimeException();
                        }
                  }
                  ois = null;
            }
             return dst;
      }



该方法可以实现深克隆,即不仅克隆对象内部的基本类型,也克隆对象内部的对象。
而与之相对的浅克隆,仅复制对象本身,而对于对象内部的对象则会复制其地址。
注:Boolean对象不会序列化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值