问题描述
在 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);
}
这篇关于为什么在java.lang.Object中保护clone()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!