Hello all,
I am trying out some test JNI code before starting a project that will use a lot of Java API from C++. I have seen old questions on the same topic and the general responses have always been you can call the getName method on a jclass instance. However, with my test code always fails to find the getName method (I have other code that works with accessing static methods, inherited methods, non-virtual invocation of super-class methods etc). Here is my code where I have tried various ways to get at the class name
void classMethod()
{
if ( ! child ) return;
jmethodID mid = env->GetMethodID( child, "getClass", "()Ljava/lang/Class;" );
if ( mid )
{
jclass clsObj = static_cast<jclass>( env->CallObjectMethod( obj, mid ) );
if ( ! clsObj ) std::cerr << "classMethod - Cannot retrieve Class object" << std::endl;
mid = env->GetMethodID( clsObj, "getName", "()Ljava/lang/String;" );
if ( mid )
{
jstring str = static_cast<jstring>( env->CallObjectMethod( clsObj, mid ) );
displayString( "classMethod", str );
}
else
{
std::cout << "classMethod - Cannot find getClass.getName, trying direct getName" << std::endl;
mid = env->GetMethodID( child, "getName", "()Ljava/lang/String;" );
if ( mid )
{
jstring str = static_cast<jstring>( env->CallObjectMethod( clsObj, mid ) );
displayString( "classMethod", str );
}
else std::cerr << "classMethod - Cannot find getClass.getName or getName directly on jclass" << std::endl;
}
}
else std::cerr << "classMethod - Cannot find getClass" << std::endl;
}
Note that if I just find "java/lang/Class" and then look up getName on it, it works fine.
Environment:
Mac OS X Mavericks
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
Thanks
Rakesh