有什么方法可以知道在 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);
无需释放,因为字符串已复制到本地缓冲区。
关于java - 我可以知道调用 JNI C 方法的类的名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719766/