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

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

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

public class MyClass implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

使用Object类的clone方法,并在类中调用super.clone()方法。

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

使用序列化和反序列化实现对象克隆。

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

阅读剩余
THE END