zoukankan      html  css  js  c++  java
  • 利用流实现类的深克隆

    利用流实现类的深克隆

    public class Test implements Serializable {
        private Entity entity;
    
        public Entity getEntity() {
            return entity;
        }
    
        public void setEntity(Entity entity) {
            this.entity = entity;
        }
    
    
        /**
         * 先将类实现序列化接口,将类写入流再读出,实际上是实现了类的深克隆
         * @throws Exception
         */
        public void writeAndReadObject() throws Exception {
            Entity entity = new Entity();
            entity.setS("111");
            Test test = new Test();
            test.setEntity(entity);
            //将对象写入流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(test);
    
            //从流中读对象
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Test t = (Test) objectInputStream.readObject();
    
            System.out.println(test.getClass() == t.getClass());//true
            System.out.println(test.getEntity()==t.getEntity());//false
            System.out.println(test.getEntity().getS().equals(t.getEntity().getS()));//true
    
        }
    
        public static void main(String[] args) throws Exception {
            Test test = new Test();
            test.writeAndReadObject();
        }
    }


    public class Entity implements Serializable {
        private String s;
    
        public String getS() {
            return s;
        }
    
        public void setS(String s) {
            this.s = s;
        }
    }
  • 相关阅读:
    HTML学习记录之HTML组成原理 PHP学习铺垫
    最长上升子序列(Longest increasing subsequence)
    进程保护(二)
    进程保护(一)
    屏幕广播的实现(三)
    vs2010 调试快捷键
    [整理]C#.Net的常见面试试题附答案(ZT)
    C# 中处理字符串常用的函数及方法详细说明
    Linux 系统下 /etc/group 档案结构
    C# Thread 多种写法总结
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/10911697.html
Copyright © 2011-2022 走看看