博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用流实现类的深克隆
阅读量:4561 次
发布时间:2019-06-08

本文共 1567 字,大约阅读时间需要 5 分钟。

利用流实现类的深克隆

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

 

转载于:https://www.cnblogs.com/BonnieWss/p/10911697.html

你可能感兴趣的文章
rabbitmq学习(四):利用rabbitmq实现远程rpc调用
查看>>
侯捷C++学习(二)
查看>>
EasyPlayer RTSP Android安卓播放器修复播放画面卡在第一帧bug
查看>>
web项目中全局常量的添加
查看>>
搬运工程 启动!
查看>>
局部加权回归(LWR) Matlab模板
查看>>
Connect to the DSP on C6A8168/DM8168/DM8148 using CCS
查看>>
hibernate在使用getCurrentSession时提示no session found for current thread
查看>>
【Luogu1471】方差(线段树)
查看>>
DEV中svg图标的使用
查看>>
markdown测试
查看>>
Java-Maven-Runoob:Maven 依赖管理
查看>>
杂项-Log:log4net
查看>>
杂项-Java:EL表达式
查看>>
tarroni music
查看>>
unity 使用RotateAround的使用注意
查看>>
[SDOI2009]HH的项链
查看>>
CodeFirst模式,容易引发数据迁移问题(不建议使用)
查看>>
jquery的colorbox关闭并传递数据到父窗
查看>>
使用Nginx、Keepalived构建文艺负载均衡
查看>>