欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

深浅拷贝,傻傻分不清

程序员文章站 2022-05-29 11:37:05
...

Cloneable接口:

jvm来看,Cloneable是一个标记接口没有什么方法签名,而clone方法是定义在Object方法中。

如果类没有实现Cloneable接口,直接调用Object的clone方法会抛出异常

Object提供clone方法是浅拷贝

实现Clone深拷贝,可以在clone方法中 直接new 生成一个新的对象,或者先clone方法出一个对象,嵌套的clone对象的属性,重复赋值给新拷贝出来的对象的属性。

另外一种方法:通过流的方法序列化方式

@Override
    protected Object clone() throws CloneNotSupportedException {

        try {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ObjectOutputStream outputStream = new ObjectOutputStream(bao);
            // 将对象输出到字节流
            // ObjectOutputStream --> ByteArrayOutputStream
            outputStream.writeObject(this);
            // 字节流 生成对象
            // byteArray --> ByteArrayInputStream --> ObjectInputStream
            ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(bis);
            return objectInputStream.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

相关标签: java java object