clone () implementation in Object class

2020-06-24 07:50发布

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 ?

标签: java clone
4条回答
forever°为你锁心
2楼-- · 2020-06-24 08:31

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

查看更多
孤傲高冷的网名
3楼-- · 2020-06-24 08:38

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楼-- · 2020-06-24 08:44

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).

查看更多
Melony?
5楼-- · 2020-06-24 08:53

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

查看更多
登录 后发表回答