java - 复制构造函数与可克隆。为什么我不应该考虑 Cloneable?

标签 java object copy-constructor cloneable

我正在读这个answer他提到了一个link ,作者解释了为什么我们不应该使用 Cloneable。但是,仍然怀疑那里所说的内容

If I have an array of Cloneable, you would think that I could run down that array and clone every element to make a deep copy of the array, but I can't. You can not cast something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method and neither does Object. If you try to cast to Cloneable and call the clone method, the compiler will say you are trying to call the protected clone method on object.

但是,我做到了

        Init s = Init.getInstance(); // getting instance
        int count=0;
        Cloneable[] v = new Cloneable[5]; // creating array
        Init x = s;
        Init y = new Init(s);
        try {
            while (count < 5) {
                v[count++] =  (Cloneable) s.clone(); // casting it.
            }

            s.setClassName("Example");
            System.out.println(((Init) v[2]).getClassName()); // Displaying.
        } catch (CloneNotSupportedException ex) {
            ex.printStackTrace();
        }

我能够创建 Cloneable 数组并且我做了作者所说的会导致错误的事情或者我误解了作者的陈述吗?任何人,请帮助我理解选择 Copy Constructor 而不是 Cloneable 的原因。

最佳答案

您不是将 s 转换为 Cloneable,然后对其调用 clone()

相反,您正在调用 s.clone(),然后将结果转换为 Clonable。 您能够这样做是因为 sInit 类型并且 Init 具有 public clone() 方法。

改为执行此操作,您会发现编译器大喊大叫,

 v[count++] =  ((Cloneable) s).clone();

现在假设你想克隆一个数组(你显然只知道它是一个 Cloneable 数组。这意味着你不知道它是实际的类型。

Cloneable[] cloneArray = new Cloneable[5];
cloneArray[i] = new Init(); // Let's say it's initialized with different type objects but all `Cloneable`.

for (Cloneable object : cloneArray) {
      object.clone(); // Compiler wont allow it. And you don't know what type it is.
}

因此,您基本上无法深度克隆 Cloneable 数组。

关于java - 复制构造函数与可克隆。为什么我不应该考虑 Cloneable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603227/

相关文章:

JavaEL : Access nested properties

java - TestNg 多个浏览器的非并行执行给出 "org.openqa.selenium.NoSuchSessionException: invalid session id"

java - 如何解决 jpa 和 hibernate 一对一注释与 doSecondPass 异常

c++ - 为类存储指向另一个类的指针复制构造函数析构函数和赋值运算符

performance - JPA+Hibernate(J2SE) @OneToMany - 数百万条记录减慢了添加新对象的速度

java - 同一对象的重量级和轻量级版本

php - 为什么从 Json 对象插入数据不起作用?

object - LabVIEW 对象

c++ - 调用对象o=13时无法调用拷贝构造函数;

c++ - 为什么复制构造函数被调用两次?