This is probably a daft question that reveals a lack of understanding of JNI. I'm writing a C++ program that encapsulates the Java VM: I'm calling functions within the VM using calls such as CallVoidMethod. That's purely background and not very relevant to the question.
I would like to be able to find the name of the Java class given a jclass instance. Is there any way to do this? Could I just call the GetName function, as I would in a Java program?
The jclass instance is your object on which a method will be invoked; you'll need to look up the getName method ID on the Class class, then invoke it on the jclass instance using CallObjectMethod to obtain a jstring result. So in short yes, you just call the getName function and look at the jstring result.
jint GetVersion(JNIEnv *env); Returns the version of the native method interface.
In software design, the Java Native Interface (JNI) is a foreign function interface programming framework that enables Java code running in a Java virtual machine (JVM) to call and be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages ...
Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.
Inspired by the accepted answer, I put a function fitting my purposes
/**
* JNI/C++: Get Class Name
* @param env [in] JNI context
* @param myCls [in] Class object, which the name is asked of
* @param fullpath [in] true for full class path, else name without package context
* @return Name of class myCls, encoding UTF-8
*/
std::string getClassName(JNIEnv* env, jclass myCls, bool fullpath)
{
jclass ccls = env->FindClass("java/lang/Class");
jmethodID mid_getName = env->GetMethodID(ccls, "getName", "()Ljava/lang/String;");
jstring strObj = (jstring)env->CallObjectMethod(myCls, mid_getName);
const char* localName = env->GetStringUTFChars(strObj, 0);
std::string res = localName;
env->ReleaseStringUTFChars(strObj, localName);
if (!fullpath)
{
std::size_t pos = res.find_last_of('.');
if (pos!=std::string::npos)
{
res = res.substr(pos+1);
}
}
return res;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With