java - 为什么 java.lang.Cloneable 没有覆盖 java.lang.Object 中的 clone() 方法?

标签 java clone cloneable

java.lang.Cloneable 接口(interface)的 Java 规范将自身定义为表示任何扩展它的对象也已经实现了 clone() 方法,该方法在其中处于 hibernate 状态java.lang.Object。具体来说,它说:

A class implements the Cloneable interface to indicate to the java.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 judiciously

The 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 a clone method, and Object's clone method is protected. You cannot, with resorting to reflection (Item 53), invoke the clone method on an object merely because it implements Cloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessible clone method.

关于java - 为什么 java.lang.Cloneable 没有覆盖 java.lang.Object 中的 clone() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9981796/

相关文章:

java - 此代码是否适用于二叉树中的欧拉之旅?

python - 适用于多只 turtle 的功能

Java - 实现 Cloneable 或添加构造函数?

java - Java的clone()方法是实现多态克隆的唯一途径吗?

java - 如何在HTML页面中嵌入android模拟器

java - 树节点可以同时是根节点和叶节点吗?

java - Android - AsyncTask 上的 RuntimeException

java - 在 Java 中克隆对象 [3 个问题]

android - 从git克隆后如何删除错误包名称和Gradle

java - 如果类没有实现可克隆,我们如何获得不可变对象(immutable对象)