gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:23:55 30 4
gpt4 key购买 nike

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

最佳答案

clone 受到保护的事实非常令人怀疑 - clone 方法未在 Cloneable 接口(interface)中声明。

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

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

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

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/1138769/

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