问题描述
我想知道以下内容:
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.)
这篇关于Cloneable 在 Java 中如何工作以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!