可克隆在Java中如何工作以及如何使用它? [英] How does Cloneable work in Java and how do I use it?

查看:57
本文介绍了可克隆在Java中如何工作以及如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下内容:

  1. Cloneable 意味着我们可以通过以下方式获得对象的克隆或副本:实现 Cloneable 接口.有什么优点和这样做的缺点?
  2. 如果对象是一个对象,那么如何进行递归克隆复合对象?
  1. Cloneable means we can have a clone or a copy of objects, by implementing the Cloneable interface. What are the advantages and disadvantages of doing that?
  2. How does the recursive cloning happen if the object is a composite 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关于使用 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中如何工作以及如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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