Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class name from jclass in JNI

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?

like image 316
Nicole Avatar asked Feb 13 '12 17:02

Nicole


People also ask

What is Jclass in JNI?

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.

What is JNIEnv * env?

jint GetVersion(JNIEnv *env); Returns the version of the native method interface.

What JNI calls?

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 ...

What is JNA vs JNI?

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.


1 Answers

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;
}
like image 57
Sam Ginrich Avatar answered Sep 19 '22 01:09

Sam Ginrich