JNI how to access Java Object (Integer)

前端 未结 2 1806
不知归路
不知归路 2020-12-24 15:49

I have a JNI method to access java method which returns an Integer object. I do not want to return the primitive int type because this code will be modified to handle Generi

相关标签:
2条回答
  • 2020-12-24 15:57

    You have to invoke the intValue method on the Integer instance to get its primitive value. Use FindClass instead of GetObjectClass (as in your code) to get a reference to the class java.lang.Integer and then GetMethodID and CallObjectMethod to actually invoke the intValue method.

    0 讨论(0)
  • 2020-12-24 16:02

    Thanks Jarnbjo,

    It works now! This is what I have:

        JNIEXPORT jint JNICALL Java_GenericPeer_print (JNIEnv *jenv, jclass jcls, jobject data){
          jclass peerCls = jenv->GetObjectClass(data);
    
         jmethodID mGetValue = jenv->GetMethodID(peerCls, "getValue","()Ljava/lang/Integer;");
         if (mGetValue == NULL){
           return(-1);
         }
    
         jobject value = jenv->CallObjectMethod(data, mGetValue);
         if(value == NULL){
          cout<<"jobject value = NULL"<<endl;
          return(-1);
         }
    
        //getValue()
    
         jclass cls = jenv->FindClass("java/lang/Integer");
         if(cls == NULL){
           outFile<<"cannot find FindClass(java/lang/Integer)"<<endl;
         }
           jmethodID getVal = jenv->GetMethodID(cls, "intValue", "()I");
           if(getVal == NULL){
             outFile<<"Couldnot find Int getValue()"<<endl;
           }
           int i = jenv->CallIntMethod(value, getVal);
    }   
    
    0 讨论(0)
提交回复
热议问题