为什么java.lang.Cloneable不覆盖java.lang.Object中的clone()方法? [英] Why does java.lang.Cloneable not override the clone() method in java.lang.Object?
问题描述
java.lang.Cloneable
接口的Java规范将其自身定义为表示扩展该对象的任何对象也已实现了 clone()
方法在 java.lang.Object
中处于休眠状态。具体来说,它表示:
The Java specification for the java.lang.Cloneable
interface defines itself as signifying that any object that extends it also has implemented the clone()
method that rests dormant within java.lang.Object
. Specifically, it says that:
一个类实现了
Cloneable
接口以指示java.lang.Object#clone()
方法,认为该方法为该类的实例进行逐域复制是合法的。
A class implements the
Cloneable
interface to indicate to thejava.lang.Object#clone()
method that it is legal for that method to make a field-for-field copy of instances of that class.
对我来说,这意味着应该假设每个扩展 Cloneable
的类其中有一个公共对象clone()
方法。这样就容易假定以下方法是有效的方法:
To me, this means that it should be assumed that every class that extends Cloneable
therefore also has a public Object clone()
method within it. This makes it easy to assume that the following is a valid method:
public static makeACloneFrom(Cloneable c)
{
return c.clone();
}
但是,事实并非如此,因为 Cloneable
源代码(没有Javadoc)
however, this is not the case, as the entirety of the Cloneable
source code (sans javadoc) is simply
package java.lang;
public interface Cloneable {
}
这意味着 Cloneable#clone()
不存在(尝试编译上面的示例方法会引发编译时错误,提示 找不到符号:方法 clone()
)。 Cloneable
的源代码是否应该包含某些影响 public Cloneable clone();
的内容?
Which means that Cloneable#clone()
does not exist (and trying to compile the example method above throws a compile-time error saying something like "cannot find symbol: method clone()
"). Shouldn't the source code of Cloneable
contain something to the effect of public Cloneable clone();
?
为什么我们不能假定实现 Cloneable
的类具有 public Cloneable克隆()
方法?
Why aren't we allowed to assume that a class that implements Cloneable
has a public Cloneable clone()
method?
推荐答案
因为它的接口设计不良。
Because it's a poorly-designed interface.
来自有效的Java (对不起,Google图书没有第二版的预览):
From Effective Java (sorry, Google Books does not have a preview for the 2nd edition):
可克隆
接口旨在用作 mixin接口(项目
18),用于广告对象允许其克隆。不幸的是,
不能达到这个目的。它的主要缺陷是缺少
clone
方法和 Object
的 clone
方法受到保护。您
不能依靠 reflection (第53项)对对象调用 clone
方法,因为实现 Cloneable
。甚至
反射调用也可能失败,因为无法保证
对象具有可访问的 clone
方法。
Item 11: Override
clone
judiciouslyThe
Cloneable
interface was intended as a mixin interface (Item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks aclone
method, andObject
'sclone
method is protected. You cannot, with resorting to reflection (Item 53), invoke theclone
method on an object merely because it implementsCloneable
. Even a reflective invocation may fail, as there is no guarantee that the object has an accessibleclone
method.
这篇关于为什么java.lang.Cloneable不覆盖java.lang.Object中的clone()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!