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
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 >

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 >
