开发者

How does clone work under the hood?

开发者 https://www.devze.com 2023-03-22 17:54 出处:网络
Clone does not call the object constructor to 开发者_开发问答create a copy of the object. So whatalgorithm does clone use ?

Clone does not call the object constructor to 开发者_开发问答create a copy of the object. So what algorithm does clone use ?

I am looking for implementation details of the native method clone. Any pointers will be appreciated.

Note that I am aware of the shortcomings of clone.


protected native Object clone(). I don't know exactly (I need to take a look at the native code) but it makes a new instance of the object inside the JVM and copies all fields.

But you should avoid using clone() - it is hard to get it right. Look at this question for more details


How it works is laid out in the Javadoc:

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

E.g., a naive, shallow field-by-field copy, very nearly (but probably not quite) just a bit-for-bit copy of the object.

I am looking for implementation details of the native method clone.

That will vary from JVM implementation to JVM implementation. It's likely to be quite an efficient operation, though, if that's your concern.


In terms of JNI, clone is (or could be) implemented using the AllocObject method which creates a new object without invoking any constructor (as opposed to NewObject). When you have the new object, reflection is used to shallowly copy all fields.

But then again, the clone/Clonable mechanism is fundamentally broken in Java. Joshua Bloch has a section about it in Effective Java. There is also several related SO questions about it.


The Object.clone() implementation is a native method that checks that the object's class implements Cloneable, and then simply allocates a new instance and does a field-by-field shallow copy. The copying is most likely done using a memory copy - there's no need for it to do anything more fancy. (But if you really want to know, look at the OpenJDK source code.)

0

精彩评论

暂无评论...
验证码 换一张
取 消