Java引用拷贝 浅拷贝 深拷贝

目录

 

引用拷贝

浅拷贝实现方式

深拷贝


引用拷贝

说白了就是两个对象指向同一引用, 改变其中一个对象的属性值时, 相对应的也会改变

浅拷贝实现方式

浅拷贝只会重新当前拷贝的对象,并不会重新生成其属性引用的对象

easy

实现 Cloneable接口 重写clone方法

@Data
public class Student implements Cloneable {

    private String name;
    private Integer age;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

深拷贝

深拷贝相比浅拷贝的不同就是,深拷贝会把拷贝的对象和其属性引用的对象都重新生成新的对象。

实现方式 bean对象实现Serializable : 把对象进行序列化后再反序列化 

工具类

public static <T> T cloneTo(T src) throws RuntimeException {
        ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        T dist = null;
        try {
            out = new ObjectOutputStream(memoryBuffer);
            out.writeObject(src);
            out.flush();
            in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray()));
            dist = (T) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return dist;
    }

猜你喜欢

转载自blog.csdn.net/weixin_44912855/article/details/113986463