对象克隆

2018-08-01  本文已影响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接口

// 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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读