为什么在 java.lang.Object 中保护了 clone() 方法? [英] Why is the clone() method protected in java.lang.Object?

查看:33
本文介绍了为什么在 java.lang.Object 中保护了 clone() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

clone()java.lang.Object 中定义为 protected 吗?

解决方案

clone 受保护的事实是非常可疑的 - clone 方法未在 中声明的事实也是如此可克隆界面.

这使得该方法对于复制数据毫无用处,因为你不能说:

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

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

ISomething i = ...if (i instanceof Cloneable) {//该死!我需要了解 ISomethingImpl!除非...copy = (ISomething) i.getClass().getMethod("clone").invoke(i);}

<块引用>

引用自 Josh Bloch 的 Effective Java:
Cloneable 接口旨在作为对象的混合接口,用于宣传它们允许克隆.不幸的是,它无法达到此目的......这是一种非常非典型的接口使用,而不是用于模拟......在为了实现接口对一个类产生任何影响,它和它的所有超类必须遵守一个相当复杂、无法执行且大部分未记录的协议"

What is the specific reason that clone() is defined as protected in java.lang.Object?

解决方案

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();
}

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);
}

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.lang.Object 中保护了 clone() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆