为什么在java.lang.Object中保护clone()方法? [英] Why is the clone() method protected in java.lang.Object?
问题描述
clone() 在 java.lang.Object
中被定义为受保护?
What is the specific reason that clone()
is defined as protected in java.lang.Object
?
推荐答案
克隆受到保护的事实非常可疑 - 事实上克隆
方法未在 Cloneable
界面中声明。
The fact that clone is protected is extremely dubious - as is the fact that the clone
method is not declared in the Cloneable
interface.
这使得该方法对于获取数据副本毫无用处,因为你不能说:
It makes the method pretty useless for taking copies of data because you cannot say:
if(a instanceof Cloneable) {
copy = ((Cloneable) a).clone();
}
我认为 Cloneable $的设计c $ c>现在在很大程度上被认为是一个错误(下面的引文)。我通常希望能够实现接口
Cloneable
,但不一定使接口 Cloneable
(类似于使用 Serializable
)。没有反思就无法做到这一点:
I think that the design of Cloneable
is now largely regarded as a mistake (citation below). I would normally want to be able to make implementations of an interface Cloneable
but not necessarily make the interface Cloneable
(similar to the use of Serializable
). This cannot be done without reflection:
ISomething i = ...
if (i instanceof Cloneable) {
//DAMN! I Need to know about ISomethingImpl! Unless...
copy = (ISomething) i.getClass().getMethod("clone").invoke(i);
}
引自 Josh Bloch的有效Java :
Cloneable接口旨在作为一个mixin接口,用于宣传他们允许克隆的对象。不幸的是,它无法达到此目的......这是一个非常不典型的用途接口而不是模拟接口...为了实现接口对类产生任何影响,它及其所有超类必须遵守相当复杂,不可执行且基本上未记录的协议
这篇关于为什么在java.lang.Object中保护clone()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!