Search code examples
javajava-native-interfacejnienv

Get jobject from jclass in JNI


I wonder if there is a way to get a jobject from a jclass? We can get the jclass from the JNIEnv call GetObjectClass(object), but I can't find anywhere to get the jobject from jclass, the reverse. In my implementation, I cache the jclass instance using the NewGlobalRef() function, but then in the new thread I need the jobject to look up the MethodID. There is no way for me to get the jobject. I ended up caching the jobject instead.


Solution

  • It is not possible to do reverse mapping because the there is not 1 : 1 relation between classes and objects. jclass represents a type whereas jobject represents an instance.

    So it is possible to get the jclass from an jobject because it means "Identify the type of the instance". But reverse operation is irrelevant. There might be more than one instance of a given type or there can be even no instance of given class.

    If you need a call a non-static method later then you have to remember a reference to the jobject.