gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:36 24 4
gpt4 key购买 nike

在一本关于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com