Why are hashCode() and getClass() native methods?

user1391940 picture user1391940 · May 14, 2012 · Viewed 13.3k times · Source

I checked the source code of Object class where I found that method declaration of getClass() was

public final native Class<?> getClass();

And the declaration of hashCode() was

public native int hashCode();

Why are these two methods native methods in the class and how can I get the source code of those methods?

Answer

Bhavik Ambani picture Bhavik Ambani · May 14, 2012

You can find the complete source code of the native methods here

I hope this will work for you.

These are native methods, because it has to interact with the machine. Here machine dependent code is written in the C language, which is not coming with the source package or in rt.jar of the lib location of the Java Runtime Environment (JRE).

One more reason for being native is possibly for the performance reasons. Due to the C level programming performance may be improved, hence they may have written the native code in the C language.

The methods are native because they concern native data. The hashCode method returns an integer value dependent on the internal representation of a pointer to an object on the heap. The getClass method must access the internal vtbl (virtual function table) that represents the compiled program's class hierarchy. Neither of these is possible with core Java.