Object类如何实现clone()方法 [英] How does Object class implement clone() method

查看:187
本文介绍了Object类如何实现clone()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一本有关Core Java的书中,我发现了这个片段:


想想
Object类的方法可以实现克隆。它
根本不知道对象,
所以它可以只使一个字段
副本。如果对象
中的所有数据字段都是数字或其他基本类型,则
复制字段就好了。但
如果对象包含对
子对象的引用,则复制字段
给你另一个引用
子对象,所以原始和
克隆的对象仍然共享一些
信息。


阅读完之后,我想知道,对我有用[0]丢个板砖[0]引用|举报|编辑删除管理回复次数:

解决方案

实际上,这是一个子类对象, clone()在本地代码中实现,所以我认为它只是做一个内存复制(复制所有字节)而不知道内容。



除此之外,还有一个Reflection API可以获得关于一个类的知识(然而,它会更慢)。


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?

解决方案

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).

这篇关于Object类如何实现clone()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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