问题描述
我正在寻找一些解释Java Cloneable
的教程,但没有得到任何好的链接,而Stack Overflow正变得越来越明显。
I was looking for some tutorials explaining about Java Cloneable
, but did not get any good links, and Stack Overflow is becoming more obvious choice anyways.
我想知道以下内容:
-
Cloneable
意味着我们可以通过
实现Cloneable
接口来获得克隆或对象副本。这样做有什么好处和
的缺点? - 如果对象是
复合对象,如何进行递归克隆?
Cloneable
means we can have a clone or a copy of objects, byimplementing theCloneable
interface. What are the advantages anddisadvantages of doing that?- How does the recursive cloning happen if the object is acomposite object?
推荐答案
你应该知道的关于 Cloneable
的第一件事是 - 不要使用它。
The first thing you should know about Cloneable
is - don't use it.
使用 Cloneable
实现克隆是非常困难的,并且努力是不值得的。
It is very hard to implement cloning with Cloneable
right, and the effort is not worth it.
而不是使用其他一些选项,例如apache-commons (深度克隆)或(浅层克隆),或者只是使用复制构造函数。
Instead of that use some other options, like apache-commons SerializationUtils
(deep-clone) or BeanUtils
(shallow-clone), or simply use a copy-constructor.
,了解Josh Bloch关于克隆<$ c的观点$ c> Cloneable ,这解释了该方法的许多缺点。 (是Sun的一名员工,并领导了众多Java功能的开发。)
See here for the views of Josh Bloch about cloning with Cloneable
, which explains the many drawbacks of the approach. (Joshua Bloch was a Sun employee, and led the development of numerous Java features.)
这篇关于关于Java cloneable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!