views:

1292

answers:

3

In java, what does the private static method registerNatives() of the Object class do?

+1  A: 

it is a JNI function which registers native implementations and Object's native methods. take a look at this explanation.

akf
+1 for the link
Tom
A: 

Since you looked at the source code to find it, it's pretty easy to guess isn't?

It's a native method, and it's called registerNatives, so I guess it registers objects with the underlying platform.

It's also private, so it's probably nothing to be concerned about.

aberrant80
You must be a closed-source programmer ("move along, nothing to look at"), not used to the idea of people actually wanting to know what goes on "under the covers". Enough said. :-P
Chris Jester-Young
Darn, was that obvious, wasn't it?
aberrant80
+6  A: 

The other answers are technically correct, but not very useful for someone with no JNI experience. :-)

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.

Here's the associated C code (from OpenJDK 6):

static JNINativeMethod methods[] = {
    {"hashCode",    "()I",                    (void *)&JVM_IHashCode},
    {"wait",        "(J)V",                   (void *)&JVM_MonitorWait},
    {"notify",      "()V",                    (void *)&JVM_MonitorNotify},
    {"notifyAll",   "()V",                    (void *)&JVM_MonitorNotifyAll},
    {"clone",       "()Ljava/lang/Object;",   (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls,
                            methods, sizeof(methods)/sizeof(methods[0]));
}

(Notice that Object.getClass is not in the list; it will still be called by the "standard" name of Java_java_lang_Object_getClass.) For the functions listed, the associated C functions are as listed in that table, which is handier than writing a bunch of forwarding functions.

Registering native functions is also useful if you are embedding Java in your C program and want to link to functions within the application itself (as opposed to within a shared library), or the functions being used aren't otherwise "exported", since these would not normally be found by the standard method lookup mechanism. Registering native functions can also be used to "rebind" a native method to another C function (useful if your program supports dynamically loading and unloading modules, for example).

I encourage everybody to read the JNI book, which talks about this and much more. :-)

Chris Jester-Young