Object类如何实现clone()方法
在一本关于 Core Java 的书中,我发现了这样的摘录:
思考一下 对象类可以实现克隆。它 对物体一无所知, 所以它只能逐个字段 复制。如果对象中的所有数据字段 是数字或其他基本类型, 复制字段就可以了。但 如果该对象包含对 子对象,然后复制字段 给你另一个参考 子对象,所以原来的和 克隆对象仍然共享一些 信息。
读完这篇文章后,我想知道Object类中的clone方法最初是如何实现的?
令我困扰的是:Object
类中的方法如何通过以下方式创建一个字段:子类对象的字段克隆,当它对该类一无所知时?
In a book on Core Java, I found this excerpt :
Think about the way in which the
Object class can implement clone. It
knows nothing about the object at all,
so it can make only a field-by-field
copy. If all data fields in the object
are numbers or other basic types,
copying the fields is just fine. But
if the object contains references to
subobjects, then copying the field
gives you another reference to the
subobject, so the original and the
cloned objects still share some
information.
After reading this I was wondering, that How is the clone method originally implemented in Object Class?
What bothers me is that: how can a method in Object
class make a field by field clone of a sub-class object, when it knows nothing about that class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,clone()是在本机代码中实现的,所以我假设它只是进行内存复制(复制所有字节)而不知道内容。
除此之外,还有 Reflection API 来获取有关类的知识(但是速度会更慢)。
Actually,
clone()
is implemented in native code, so I assume it just does a memory copy (copy all the bytes) without knowing the contents.Besides that, there is the Reflection API to gain knowlegde about a class (which would be slower, however).
从 阅读此内容Javadoc:
意味着当你的对象中有一个子对象时,你不应该仅仅克隆/复制它的引用,而应该克隆/复制该对象的内部结构(为了创建它的新实例),如果每个对象都有它的clean clone() 方法,您将能够像父对象一样克隆它,否则您将必须创建它的新实例并一一复制其内部预设字段。
Read this from the Javadoc:
Means when you have a subobject in your object you shouldnt just clone/copy its reference but the internal structure of this object (in order to create a new instance of it), if each object has its clean clone() methode you will be able to clone it like the parent object otherwise you will have to create a new instance of it and copy its internal premitive fields one by one.