我应该在Java中使用Clone方法吗? [英] Should I use Clone method in java?

查看:77
本文介绍了我应该在Java中使用Clone方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说您应该在代码中避免使用它,但是由于某种原因实现了它,因此是否存在使用它实际上是一个好选择(还是不错的选择)还是我应该总是尝试避免它的情况?

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?

推荐答案

乔什·布洛赫(Josh Bloch)完美地回答了这个问题:

如果您已经阅读了我书中有关克隆的内容,尤其是如果您阅读这句话,你会知道我认为克隆是深深的破碎的.有一些设计缺陷,其中最大的缺陷是可克隆的接口没有克隆方法.那就意味着根本行不通:制作可克隆内容并没有说什么关于你可以做什么.相反,它说了些什么它可以在内部进行.它说如果通过调用super.clone反复地,它最终调用了Object的clone方法,该方法将返回原始的字段副本.

If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.

但是它并没有说明您可以使用的对象实现Cloneable接口,这意味着您不能执行多态克隆操作.如果我有一个Cloneable数组,你会认为我可以耗尽该数组并克隆每个元素复制数组的深层副本,但我做不到.你不能投可以克隆的东西,并调用clone方法,因为Cloneable没有公共的克隆方法,对象也没有.如果你试试强制转换为Cloneable并调用clone方法,编译器会说您正在尝试在对象上调用受保护的克隆方法.

But it doesn't say anything about what you can do with an object that implements the Cloneable interface, which means that you can't do a polymorphic clone operation. If I have an array of Cloneable, you would think that I could run down that array and clone every element to make a deep copy of the array, but I can't. You cannot cast something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method and neither does Object. If you try to cast to Cloneable and call the clone method, the compiler will say you 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 original Java APIs were done very quickly under a tight deadline to meet a closing market window. The original Java team did an incredible job, but not all of the APIs are perfect. Cloneable is a weak spot, and I think people should be aware of its limitations.

这篇关于我应该在Java中使用Clone方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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