Linux 拨号vps windows公众号手机端

java实现对象克隆的方法有哪些

lewis 8年前 (2017-03-09) 阅读数 7 #程序编程
文章标签 Java

在Java中实现对象克隆的方法有以下几种:

  1. 实现Cloneable接口,并重写clone方法。

    public class MyClass implements Cloneable {
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    
  2. 使用Object类的clone方法,并在类中调用super.clone()方法。

    public class MyClass {
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    
  3. 使用序列化和反序列化实现对象克隆。

    public class MyClass implements Serializable {
        public MyClass clone() {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(this);
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bais);
                return (MyClass) ois.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    

需要注意的是,如果要实现深拷贝(即克隆对象和原对象不共享引用),需要在clone方法中对引用类型的成员变量进行克隆操作。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门