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;
        }
    }
  • 相关阅读:
    java内存溢出
    jstack命令使用
    JVM问题排查步骤
    c++指针常量和常量指针
    c++ 通讯录
    冒泡排序
    翻转数组
    敲桌子
    求一个100-999之间的水仙花数
    elasticsearch 模板的使用
  • 原文地址:https://www.cnblogs.com/BonnieWss/p/10911697.html
Copyright © 2011-2022 走看看