Java的两种深拷贝(原型模式)

本文介绍两种实现深克隆的方法:覆盖clone()方法和使用序列化。通过实现Cloneable接口并重写clone()方法实现对象的浅复制,再通过深复制解决内部对象的复制问题。此外,还介绍了通过序列化实现深复制的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

克隆

  • 实现Cloneable
  • 重写clone()方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepPrototype deepPrototype = null;
        deepPrototype = (DeepPrototype) super.clone();
        deepPrototype.target = (DeepCloneableTarget) this.target.clone();

        return deepPrototype;
    }

序列化(推荐)

  • 实现Serializable
  • 定义serialVersionUID
    public DeepPrototype deepClone() {

        //创建流
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{
            //将本类输出到内存中
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //从内存中读取
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype o = (DeepPrototype) ois.readObject();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) bos.close();
                if (oos != null) oos.close();
                if (bis != null) bis.close();
                if (ois != null) ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
将序列化的类输出到本地文件
    public static void cloneFile() throws IOException, ClassNotFoundException {
        //序列化到本地
        FileOutputStream fos = new FileOutputStream("E:/ProgramData/Project/Object.out");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        DeepCloneableTarget target = new DeepCloneableTarget("李四", "张三");
        oos.writeObject(target);
        oos.flush();
        oos.close();
        fos.close();

        //读取本地序列化后的文件
        FileInputStream fis = new FileInputStream("E:/ProgramData/Project/Object.out");
        ObjectInputStream ois = new ObjectInputStream(fis);
        target = (DeepCloneableTarget) ois.readObject();
        ois.close();
        fis.close();
        System.out.println(target);
    }

整体代码

public class DeepCloneableTarget implements Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    private String cloneName;
    private String cloneClass;

    public DeepCloneableTarget(String cloneName, String cloneClass) {
        this.cloneName = cloneName;
        this.cloneClass = cloneClass;
    }

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

    @Override
    public String toString() {
        return "DeepCloneableTarget{" +
                "cloneName='" + cloneName + '\'' +
                ", cloneClass='" + cloneClass + '\'' +
                '}';
    }
}
public class DeepPrototype implements Serializable, Cloneable {

    private static final long serialVersionUID = -1897843806793850888L;

    public String name;
    public DeepCloneableTarget target;

    public DeepPrototype() {
    }

    /**
     * 深拷贝  clone(),序列化
     *  方式一
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepPrototype deepPrototype = null;
        deepPrototype = (DeepPrototype) super.clone();
        deepPrototype.target = (DeepCloneableTarget) this.target.clone();

        return deepPrototype;
    }

    /**
     * 深拷贝
     *  方式二: 序列化
     */
    public DeepPrototype deepClone() {

        //创建流
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{
            //将本类输出到内存中
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //从内存中读取
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype o = (DeepPrototype) ois.readObject();
            return o;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (bos != null) bos.close();
                if (oos != null) oos.close();
                if (bis != null) bis.close();
                if (ois != null) ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值