java - 为什么java.lang.Object中的clone()方法受到保护?

标签 java oop clone

clone()具体原因是什么?在 java.lang.Object 中被定义为 protected?

最佳答案

克隆受到保护的事实非常可疑 - 正如 clone 方法未在 Cloneable 接口(interface)中声明的事实一样。

这使得该方法对于获取数据副本毫无用处,因为你不能说:

if(a instanceof Cloneable) {
    copy = ((Cloneable) a).clone();
}

我认为Cloneable的设计现在在很大程度上被认为是一个错误(引文如下)。我通常希望能够实现接口(interface)Cloneable,但不一定使接口(interface)Cloneable(类似于使用Serialized)。没有反射(reflection)就无法做到这一点:

ISomething i = ...
if (i instanceof Cloneable) {
   //DAMN! I Need to know about ISomethingImpl! Unless...
   copy = (ISomething) i.getClass().getMethod("clone").invoke(i);
}

Citation From Josh Bloch's Effective Java:
"The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately it fails to serve this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order for implementing the interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable and largely undocumented protocol"

关于java - 为什么java.lang.Object中的clone()方法受到保护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314468/

相关文章:

python oop多态性

Java : Questions on clone method

java - 参数化类 'ABC' 的原始使用

java - Java 中的 OOP : Class inheritance with method chaining

python - type() 和 isinstance() 有什么区别?

java.util.Date 克隆或复制以不暴露内部引用

c - 模拟 vfork 与克隆

java - Gradle + Dropwizard + Shadow -> 无法找到或加载主类

Java - 使用现有的 PublicKey.sql 加密字符串

java - 以编程方式创建的 TestNG XML 不执行测试用例