clone () implementation in Object class

2020-06-24 08:24发布

问题:

I was reading this article and it says that

Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor".

All I see in the grep code is the following line :

protected native Object clone() throws CloneNotSupportedException;

What am I missing here ?

回答1:

You're missing the native which means it's implemented in non-Java code (in this case it's implemented in the JVM itself).

That's because the exact functionality of clone can not be implemented in Java code (which makes it so problematic).



回答2:

The native keyword indicates that the implementation is in native (non-Java) code.



回答3:

First of all, to actually understand the concept behind clone better I recommend the answer to the question: How to properly override clone method?

Regarding the source code you have put into your question:

native means here, that this is a method which is not implemented with Java, but with another language, often C or C++. It's still part of the JVM, hence you can find the actual implementation in the OpenJDK™ Source Release in the

"openjdk/hotspot/src/share/vm/prims/jvm.cpp":539

JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
  JVMWrapper("JVM_Clone");
  Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
  const KlassHandle klass (THREAD, obj->klass());
  JvmtiVMObjectAllocEventCollector oam;
  .
  .
  .
JVM_END


回答4:

The method is marked as native, so you cannot see its implementation because it is not in Java.



标签: java clone