How getClass () is implemented in java?

I have a code like this:

public class QueueSample { public static void main(String[] args) { System.out.println(new QueueSample().getClass()); } } 

he prints:

 class QueueSample 

getClass() method comes from the Object class. After looking at the source code for Object , I can only see the method definition as follows:

 public final native Class<?> getClass(); 

If it is not implemented here, where and how was this method implemented?

+7
java
source share
1 answer

As @TheLostMind mentions, you can get the source code from OpenJDK - looking at a slightly newer version (JDK9) , getClass() own method is implemented as

 JNIEXPORT jclass JNICALL Java_java_lang_Object_getClass(JNIEnv *env, jobject this) { if (this == NULL) { JNU_ThrowNullPointerException(env, NULL); return 0; } else { return (*env)->GetObjectClass(env, this); } } 

So basically, he delegates the JVM environment and uses the GetObjectClass() function to return the Class object. You can use this as a starting point - if you want to go deeper, I suggest you check out the JDK source code from http://hg.openjdk.java.net/ using mercurial so you can view it.

As @Holger mentions, there are some performance optimizations when using a JIT compiler such as hotspot - for example, Performance methods used in the JVM Hotspot says: " Object.getClass() is one or two instructions." This means that the code above shows one possible implementation of Object.getClass() , but this implementation may change at runtime and / or based on the actual JVM (interpreted / JITted, client / server, Oracle / JRockit standard ...)

+5
source share

All Articles