How does clone work under the hood?

后端 未结 4 676
小鲜肉
小鲜肉 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:45

    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.

提交回复
热议问题