Cloneable不覆盖java

Cloneable不覆盖java

本文介绍了为什么java.lang.Cloneable不覆盖java.lang.Object中的clone()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 的类其中有一个公共对象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.

来自(对不起,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 方法。

这篇关于为什么java.lang.Cloneable不覆盖java.lang.Object中的clone()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:15