gpt4 book ai didi

java - 了解非最终类的克隆方法

转载 作者:行者123 更新时间:2023-11-30 08:10:43 24 4
gpt4 key购买 nike

我正在阅读 J. Bloch 的 effective 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 说它可以创建子类?您不能从 javadoc 中解释它的含义吗(我自己看不出来)。

最佳答案

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

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]

关于java - 了解非最终类的克隆方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31533122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com