Java深浅拷贝

  |   0 评论   |   0 浏览
package shejimoshi.prototype;

import java.io.*;

public class Prototype implements Cloneable, Serializable {
    private String name ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * 浅拷贝
     * @return
     * @throws CloneNotSupportedException
     */
    public Object shallowClone() throws CloneNotSupportedException {
        Prototype prototype = (Prototype) super.clone();
        return prototype;
    }
    /**
     * 深拷贝
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Object deepClone() throws IOException, ClassNotFoundException {
        /**
         * 将对象序列化到二进制流
         */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(bos);
        outputStream.writeObject(this);

        /**
         * 从二进制流中读出产生的新对象
         */
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return objectInputStream.readObject();
    }
}


标题:Java深浅拷贝
作者:码农路上
地址:https://wujingjian.club/articles/2020/08/04/1596526303892.html