jclass, jmethodID, and jfieldID scope

I've researched a bunch of documentation, and I can't figure out how long these objects stick around. It's

obvious with jobject that you need to use env->NewGlobalRef() to keep it around, but if I use

env->GetObjectClass() on the global reference I've created then is it also global or do I need to call

GetObjectClass() every time I enter my code? I also have the same questions if I use GetMethodID() or

GetFieldID on the global reference.

Can anyone shed any light on this?

Bryan

[549 byte] By [bryanhilterbrand] at [2007-9-26 11:14:16]
# 1

jclass is just a subclass of jobject (just as java.lang.Class is a subclass of java.lang.Object). GetObjectClass() will return a local reference. If you want to use the jclass across multiple threads or multiple calls into the JNI code you need to create a global reference to it with NewGlobalRef() and then cast it back to a jclass.

jmethodID and jfieldID remain valid as long as the ClassLoader that loaded their class remains loaded. Unless you are doing something tricky with ClassLoaders, then the field and method ids will remain valid forever.

daney at 2007-7-2 0:14:40 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 2
Thanks for that insight -- that helps a lot! One more question: can I use the same jmethodID for calling a method on several different instances of the same object?
bryanhilterbrand at 2007-7-2 0:14:40 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 3

The jmethodID and jfieldID are for ALL instances of the class that is their context. In fact since getting the values of the ids can be time consuming, I usually call a static JNI init method from the class static initializer that gets all of the jmethodID and jfieldIDs that will be used in the entire JNI library. These are then stored in global variables and can then be used from anywhere in the native code.

I hope that makes sense.

daney at 2007-7-2 0:14:40 > top of Java-index,Java HotSpot Virtual Machine,Specifications...