利用流实现类的深克隆

利用流实现类的深克隆

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

 

posted @ 2019-05-23 14:31  第二人生Bonnie  阅读(231)  评论(0编辑  收藏  举报