[ACCEPTED]-Class name from jclass in JNI-java-native-interface

Accepted answer
Score: 16

The jclass instance is your object on which a 6 method will be invoked; you'll need to look 5 up the getName method ID on the Class class, then invoke 4 it on the jclass instance using CallObjectMethod to obtain a jstring result.

So 3 in short yes, you just call the getName function 2 and look at the jstring result.


(error handling 1 elided)

JNIEnv* env = ...;
// substitute your desired class's specifier for "java/lang/Class"...
jclass cls = env->FindClass("java/lang/Class"); 
jmethodID mid_getName = env->GetMethodID(cls, "getName", "()Ljava/lang/String;");
jstring name = env->CallObjectMethod(cls, mid_getName);
Score: 2

Inspired by the accepted answer, I put a 1 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;

More Related questions