Java: Rationale of the Cloneable interface

女生的网名这么多〃 提交于 2019-11-26 08:26:57

问题


Why wasn\'t the .clone() method specified in the java.lang.Cloneable interface ?


回答1:


Basically, it's a broken interface. Ken Arnold and Bill Venners discussed it in Java Design Issues.

Arnold:

If I were to be God at this point, and many people are probably glad I am not, I would say deprecate Cloneable and have a Copyable, because Cloneable has problems. Besides the fact that it's misspelled, Cloneable doesn't contain the clone method. That means you can't test if something is an instance of Cloneable, cast it to Cloneable, and invoke clone. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.




回答2:


See this bug in the Java bugs database:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4098033

Essentially, this is a design flaw in earlier versions of Java that they are not intending to fix in the Cloneable interface as to do so would break compatibility with some existing code.




回答3:


In Java, there is this concept of marker interfaces. The Cloneable interface has no methods or fields and serves only to identify the semantics of being cloneable.

from the dev-x website:

Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:

  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener



回答4:


On the project I work on, we've created an interface called PublicCloneable, it contains the clone method and specifies that it is public.

I find this one useful: the fact that there's a clone method, but you cannot access it doesn't help very much.

public interface PublicCloneable extends Cloneable {
    public Object clone();
}



回答5:


Because the clone method is implemented in the Object class due to its "special" condition: the memory copy of objects of any kind.



来源:https://stackoverflow.com/questions/709380/java-rationale-of-the-cloneable-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!