我可以知道调用JNI C方法的类的名称吗?

有什么方法可以知道在JNI C代码中调用方法的类的名称吗? 我可以使用以下语句获取对类的引用:

jclass cls = (*env)->GetObjectClass(env,obj); 

但有什么办法可以知道class级的名字吗? 。

此代码将为您提供调用类名称:

 jclass cls = env->GetObjectClass(obj); // First get the class object jmethodID mid = env->GetMethodID(cls, "getClass", "()Ljava/lang/Class;"); jobject clsObj = env->CallObjectMethod(obj, mid); // Now get the class object's class descriptor cls = env->GetObjectClass(clsObj); // Find the getName() method on the class object mid = env->GetMethodID(cls, "getName", "()Ljava/lang/String;"); // Call the getName() to get a jstring object back jstring strObj = (jstring)env->CallObjectMethod(clsObj, mid); // Now get the c string from the java jstring object const char* str = env->GetStringUTFChars(strObj, NULL); // Print the class name printf("\nCalling class is: %s\n", str); // Release the memory pinned char array env->ReleaseStringUTFChars(strObj, str); 

请注意,我没有采取任何措施来检查错误。 这只是一个小代码片段,描述了如何完成它。


或者,您可以执行此操作,而不是使用GetStringUTFChars/ReleaseStringUTFChars

 // Make sure that the buffer is large enough char str[128]; jint strlen = env->GetStringUTFLength(strObj); env->GetStringUTFRegion(strObj, 0, strlen, str); printf("\nCalling class is: %s\n", str); 

无需释放,因为字符串被复制到本地缓冲区。

在我的情况下,我还没有获得课程的对象。 相反,我想根据其签名获取给定类的名称。

所以,这对我有用。 我希望它可以帮助:

 // Find the class by its JNI signature jclass cls = env->FindClass(expectedType); // Get the class object's class descriptor jclass clsClazz = env->GetObjectClass(cls); // Find the getSimpleName() method in the class object jmethodID methodId = env->GetMethodID(clsClazz, "getSimpleName", "()Ljava/lang/String;"); jstring className = (jstring) env->CallObjectMethod(cls, methodId); // And finally, don't forget to release the JNI objects after usage!!!! env->DeleteLocalRef(clsClazz); env->DeleteLocalRef(cls); 

只需通过JNI调用jclass上的getName()