Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jni call to getClass returns null for a jobject

I am facing issues with making a java call from C++ code using JNI. I am able to get the jobject, but the invoocation of any API on the jobject fails. On digging for nearly one day and comparing with other working Java API (jobjects which i call in my code), i found one difference.

the following piece of code

void printClassInfo(JNIEnv* env, jobject object, jclass klazz)
{
    printf("printclass info 1\n");
    printf("printclass info 2\n");

    // First get the class object
    jmethodID mid = env->GetMethodID(klazz, "getClass", "()Ljava/lang/Class;");
    printf("printclass info 2.1\n");
    jobject clsObj = env->CallObjectMethod(object, mid);
    printf("printclass info 3\n");
    if(clsObj == NULL){
        printf("cls obj is null");
    }
}

prints cls obj is null for the jobject for which I am seeing issues.

For other jobjects, the call does not return null.

The major difference is that it is a newly added class and I seemed to have missed something that can cause this issue. I have rechecked again and again but not getting any clear indicators.

Any help appreciated.

like image 717
Gaurav Abbi Avatar asked Mar 20 '14 10:03

Gaurav Abbi


People also ask

What is Jclass in JNI?

typedef jobject jclass; In C++, JNI introduces a set of dummy classes to enforce the subtyping relationship. For example: class _jobject {}; class _jclass : public _jobject {}; ...

What is JNIEnv * env?

jobject NewGlobalRef(JNIEnv *env, jobject obj); Creates a new global reference to the object referred to by the obj argument. The obj argument may be a global or local reference.

What is GetStringUTFChars?

GetStringUTFChars converts the built-in Unicode representation of a Java string into a UTF-8 string. Once you are certain that the string only contains 7-bit ASCII characters, you can directly pass the string to regular C language functions, such as printf , as is shown in Prompt.

Is JNI fast?

When talking about JNI, there are two directions: java calling C++, and C++ calling java. Java calling C++ (or C) via the "native" keyword is very fast, around 50 clock cycles. However, C++ calling Java is somewhat slow.


1 Answers

You have the object already. Why do you need its class (sorry klass) at all? JNI has a nic function for you, GetObjectClass(jobject). Here is what you could do:

void printClassInfo(JNIEnv* env, jobject object) {

   jclass clsObj = env->GetObjectClass(env, object);
   if (clsObj == NULL) {
    printf("cls obj is null");
   }
}

Will this solve your problem?

like image 142
Alex Cohn Avatar answered Sep 20 '22 07:09

Alex Cohn