gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:04 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com