java.lang.Cloneable
接口(interface)的 Java 规范将自身定义为表示任何扩展它的对象也已经实现了 clone()
方法,该方法在其中处于 hibernate 状态java.lang.Object
。具体来说,它说:
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
的类因此也有一个 public Object clone()
方法。这使得很容易假设以下是一个有效的方法:
public static makeACloneFrom(Cloneable c)
{
return c.clone();
}
然而,事实并非如此,因为整个 Cloneable
源代码(没有 javadoc)很简单
package java.lang;
public interface Cloneable {
}
这意味着 Cloneable#clone()
不存在(并且尝试编译上面的示例方法会引发编译时错误,提示类似“找不到符号:方法克隆( )
")。 Cloneable
的源代码不应该包含一些类似于 public Cloneable clone();
的东西吗?
为什么我们不允许假设实现 Cloneable
的类具有 public Cloneable clone()
方法?
最佳答案
因为它是一个设计糟糕的界面。
来自 Effective Java (抱歉,Google 图书没有第 2 版的预览):
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 - 为什么 java.lang.Cloneable 没有覆盖 java.lang.Object 中的 clone() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9981796/