了解非最终的克隆方法 类

Understanding clone method for non-final classes

我正在阅读 J. Bloch 的有效 java,现在我在第 39 节(制作防御性副本)。他提到通过clone方式做防御副本不好,因为:

Note also that we did not use Date’s clone method to make the defensive copies. Because Date is nonfinal, the clone method is not guaranteed to return an object whose class is java.util.Date: it could return an instance of an untrusted subclass specifically designed for malicious mischief.

强调的语句对我来说不是很明显。实际上,让我们与 javadocs 进行比较。没有任何关于创建子类的参考。我们唯一可以确定的是:

this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned.

那么为什么 J. Bloch 说它可以创建 子类?你不能从 java 文档中解释它的含义吗(我自己看不出来)。

它隐含在 Javadocs 引用中:"this" 对象的 class 可以是引用该对象的变量声明类型的子 class(由于多态性) . clone 方法受到保护,因此可以在某个 class.

的子 class 中调用它
public class Test {
    public static void main(String[] args) throws Exception {
        Foo foo = new Bar();
        Foo copyOfFoo = createCopyOfFoo(foo);
        System.out.println(copyOfFoo);
    }


    private static Foo createCopyOfFoo(Foo foo) throws CloneNotSupportedException {
        Foo clone = (Foo) foo.clone();
        return clone;
    }
}

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

class Bar extends Foo {
    private int x = 1;

    @Override
    public String toString() {
        return "Bar [x=" + x + "]";
    }
}

输出:

Bar [x=1]