java - Object类如何实现clone()方法

标签 java class object clone core

在一本关于 Core Java 的书中,我找到了这段摘录:

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.

看完后我想知道,对象类中的克隆方法最初是如何实现的?

令我困扰的是:Object 类中的方法如何在对子类对象一无所知的情况下逐字段克隆子类对象?

最佳答案

实际上,clone() 是在 native 代码中实现的,所以我假设它只是在不知道内容的情况下进行内存复制(复制所有字节)。

除此之外,还有 Reflection API 来获取有关类的知识(但是速度会较慢)。

关于java - Object类如何实现clone()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5375311/

相关文章:

Flash AS3 - 库中相同基类的对象 - 类型强制失败

javascript - 变量返回 [object HTMLParagraphElement]

Java getBytes UTF-8编码

java - 如何通过 asynctask 暂停下载过程

java - Spring 启动,MySQL : How to do a database authentication with a hashed password?

java RXTX 发送字符串

php - 在 CodeIgniter 中找不到错误类 Controller

C# - 需要基类上的接口(interface),但只需要派生类中的实现

javascript object.key 不工作

c# - 在 for/foreach 循环中声明相同的对象