Search code examples
javacjava-native-interface

Get Jclass or jobject from jobject array JNI


I have my below Java code where Array is a custom object.

public native int pax_store_get_data_avail_info(DataAvailable[] stats_array);

My JNI Generated file is

    JNIEXPORT jint JNICALL Java_demo_JNIWrapper_pax_1store_1get_1data_1avail_1info
      (JNIEnv *env, jclass jclass1, jobjectArray jobj){
}

I want to populate jobjectArray inside the JNI ,and when I tried using my implemention my program crashed .

JNIEXPORT jint JNICALL Java_demo_JNIWrapper_pax_1store_1get_1data_1avail_1info
  (JNIEnv *env, jclass jclass1, jobjectArray jobj){


struct pax_store_data_avail_stat_s test_stat [2] ;

    int i;

    test_stat [0].time = 1460332625;  //  4/10/2016, 4:57:05 PM
    test_stat [0].bytes_in_this_second = 20;

    test_stat [1].time = 1460332626;   //  4/10/2016, 4:57:06 PM 
    test_stat [1].bytes_in_this_second = 30;
    jclass dataClass=(*env)->GetObjectClass(env,"demo/DataAvailable");//Crash Over here 

I was not able to get the Object Class .So taught on if I get the jclass or jobject from the Jobject Array .

Are there any other methods from which I can populate the Jobject Array inside the JNI code .


Solution

  • Given a jobject you can use GetObjectClass to retrieve the class of the object:

    jobject object = ...
    jclass c =(*env)->GetObjectClass(env, object);
    

    Obviously passing a class name does not work. Instead - given a class name - use FindClass to obtain the jclass:

    jclass c =(*env)->FindClass(env, "demo/DataAvailable");