问题描述
我想知道以下内容:
-
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 SerializationUtils
(深克隆)或 BeanUtils
(浅克隆),或者只是使用复制构造函数.
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关于使用 Cloneable
,它解释了该方法的许多缺点.( Joshua Bloch 是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中如何工作以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!