0

I was trying to answer a question about extending the Object class and overriding the toString method, when I noticed that some methods in the Object class are defined as native, which means that their implementations are OS dependant and thought about asking those 2 questions:

Why are some methods in the class Object defined as native methods?

And what does registerNatives method do exactly?

Rami
  • 7,162
  • 1
  • 22
  • 19

3 Answers3

1

The native methods are the ones that need to hook into the JVM internals, such as clone(), which needs to tell the JVM to copy the base memory structures of whatever object is being cloned.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

I hope this will work for you.

There are some native methods in the Object class, 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.

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

Coming to your second question:-

Normally, in order for the JVM to find your native functions, they have to be named a certain way. e.g., for java.lang.Object.registerNatives, the corresponding C function is named Java_java_lang_Object_registerNatives. By using registerNatives (or rather, the JNI function RegisterNatives), you can name your C functions whatever you want.

Ashrumochan
  • 198
  • 3
  • 8
1

Some methods in Java are native because of two reasons (that I can see):

  1. They require resources that are not readily exposed via Java itself. For instance, 'getClass()' makes use of some low-level C routines to refer to the object class, which leads me into the second reason...
  2. For efficiency reasons. Since runtime speed is so important, implementing hashCode(), getClass(), etc. natively offers incredible opportunity to boost speed in object creation, which if implemented in Java itself, would gum up the object handling so much that it would make Java unusable.

As for registerNatives, refer to: What does the registerNatives() method do?.

Community
  • 1
  • 1
Danny Daglas
  • 1,501
  • 1
  • 9
  • 9