gpt4 book ai didi

java - 克隆时调用构造函数

转载 作者:行者123 更新时间:2023-12-02 04:34:21 25 4
gpt4 key购买 nike

这里引用了Effective Java:

Here it is, copied from the specification for java.lang.Object [JavaSE6]:

Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. The general intent is that, for any object x, the expression

x.clone() != x 

will be true, and the expression

x.clone().getClass() == x.getClass() 

will be true, but these are not absolute requirements. While it is typically the case that

x.clone().equals(x) 

will be true, this is not an absolute requirement. Copying an object will typically entail creating a new instance of its class, but it may require copying of internal data structures as well. No constructors are called.

现在让我们看看 JavaSE6 javadocs

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:

x.clone() != x will be true,

and that the expression:

x.clone().getClass() == x.getClass() 

will be true, but these are not absolute requirements. While it is typically the case that:

x.clone().equals(x) 

will be true, this is not an absolute requirement.

他在哪里找到强调的文字?有什么要求吗?

最佳答案

克隆通常被视为深层复制。如果只克隆“主对象”,它的成员对象就不会是深拷贝。因此,为了正确地进行克隆,您必须遍历整个对象层次结构并克隆所有可克隆的成员。

使用clone()通常是一个坏主意,而且非常麻烦。相反,序列化和反序列化对象图会更方便。在这种情况下也不会调用构造函数。

关于java - 克隆时调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022105/

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