Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the getClass() is implemented in java?

Tags:

java

I have a code like this :

public class QueueSample {

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

}

it prints:

class QueueSample

getClass() method is coming from the Object class. Looking at the source code of Object, I can see only method definition like this:

public final native Class<?> getClass();

If its not implemented here, where and how does this method got implemented?

like image 557
batman Avatar asked Oct 29 '14 09:10

batman


People also ask

How does getClass work in Java?

getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

What does getClass () getName () Do Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object.

Can we override getClass method?

You cannot override getClass .

How do you return a class name in Java?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.


1 Answers

As @TheLostMind mentions, you can get the source code from OpenJDK - looking into a somewhat newer version (JDK9), the getClass() native method is implemented like

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, essentially what it does is it delegates to the JVM's 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 that you check out the JDK source code from http://hg.openjdk.java.net/ using mercurial, so that you can browse through it.

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

like image 131
Andreas Fester Avatar answered Sep 26 '22 17:09

Andreas Fester