美文网首页
对象克隆

对象克隆

作者: 皮皮咕 | 来源:发表于2018-08-01 14:38 被阅读0次

    实现Cloneable接口

    // 1.实现Cloneable接口
    public class Tmp implements Cloneable {
        // 2.编写浅复制方法
        public Tmp clone() {
            Tmp tmp = null;
            try {
                // 3.调用父类的clone方法
                tmp = (Tmp)super.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return tmp;
        }
    }
    

    实现Serializable接口

    • 关键字transient--该元素不会进行jvm默认的序列化,不过可以自己完成序列化(节省运行资源)
    • 若父类实现了Serializable接口,其子类均可以序列化,当反序列化的时候,不会调用构造函数
    • 若子类实现了Serializable接口,但父类没有实现,当反序列化的时候,会执行父类的构造函数
    // 1.实现Serializable接口
    public class Tmp implements Serializable, Cloneable {
        // 2.编写深复制方法
        public Tmp deepClone() {
            ByteOutputStream byteOutputStream = null;
            ObjectOutputStream objectOutputStream = null;
            ByteInputStream byteInputStream = null;
            ObjectInputStream objectInputStream = null;
            try {
                // 3.创建输出流(序列化)
                byteOutputStream = new ByteOutputStream();
                objectOutputStream = new ObjectOutputStream(byteOutputStream);
                objectOutputStream.writeObject(this);
                // 4.创建输入流(反序列化)
                byteInputStream = new ByteInputStream(byteOutputStream.getBytes(), byteOutputStream.getBytes().length);
                objectInputStream = new ObjectInputStream(byteInputStream);
                Tmp tmp = (Tmp)objectInputStream.readObject();
                return tmp;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (byteOutputStream != null) {
                    try {
                        byteInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (objectOutputStream != null) {
                    try {
                        objectOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (byteInputStream != null) {
                    try {
                        byteInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (objectInputStream != null) {
                    try {
                        objectInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    }

    相关文章

      网友评论

          本文标题:对象克隆

          本文链接:https://www.haomeiwen.com/subject/zwfrvftx.html