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

avatar
作者
筋斗云
阅读量:0

在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方法中对引用类型的成员变量进行克隆操作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!