问题描述
我听说您应该在代码中避免使用它,但是由于某种原因实现了它,因此是否存在使用它实际上是一个好选择(还是不错的选择)还是我应该总是尝试避免它的情况?
I heard that you should avoid it in your code but it was implemented for some reason so is there a case where using it is actually a good (or not bad) choice or should I always try to avoid it?
推荐答案
但是它并没有说明您可以使用的对象实现Cloneable接口,这意味着您不能执行多态克隆操作.如果我有一个Cloneable数组,你会认为我可以耗尽该数组并克隆每个元素复制数组的深层副本,但我做不到.你不能投可以克隆的东西,并调用clone方法,因为Cloneable没有公共的克隆方法,对象也没有.如果你试试强制转换为Cloneable并调用clone方法,编译器会说您正在尝试在对象上调用受保护的克隆方法.
But it doesn't say anything about what you can do with an object thatimplements the Cloneable interface, which means that you can't do apolymorphic clone operation. If I have an array of Cloneable, youwould think that I could run down that array and clone every elementto make a deep copy of the array, but I can't. You cannot castsomething to Cloneable and call the clone method, because Cloneabledoesn't have a public clone method and neither does Object. If you tryto cast to Cloneable and call the clone method, the compiler will sayyou are trying to call the protected clone method on object.
可克隆性被破坏是可耻的,但是它确实发生了.原本的Java API在紧迫的期限内很快就完成了,以满足关闭市场窗口.最初的Java团队做得非常出色,但并非所有的API都是完美的.可克隆性是一个薄弱环节,而我认为人们应该意识到它的局限性.
It's a shame that Cloneable is broken, but it happens. The originalJava APIs were done very quickly under a tight deadline to meet aclosing market window. The original Java team did an incredible job,but not all of the APIs are perfect. Cloneable is a weak spot, and Ithink people should be aware of its limitations.
这篇关于我应该在Java中使用Clone方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!