How does clone work under the hood?

后端 未结 4 667
小鲜肉
小鲜肉 2020-12-02 02:05

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

4条回答
  •  温柔的废话
    2020-12-02 02:44

    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.

提交回复
热议问题