使用以下代码,我可以调用静态方法(所以假设我的类路径是正确的),但是JNI GetMethodID方法在同一个类中找不到构造函数:
java_test.cpp C ++ MWE:
#include <jni.h>
#include <cstring>
int main( void )
{
JNIEnv * env;
JavaVM * jvm;
JavaVMOption options[1];
JavaVMInitArgs vm_args;
long status;
options[0].optionString = (char*)"-Djava.class.path=/home/kadmin/workspace/kata/JavaTest/build/classes";
memset( &vm_args, 0, sizeof( vm_args ) );
vm_args.version = JNI_VERSION_1_2;
vm_args.nOptions = 1;
vm_args.options = options;
status = JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args );
if ( status == JNI_ERR )
{
return 1;
}
/* Call static method to cube x */
jclass cls = env->FindClass( "javatest/Sample" );
jmethodID int_method_id = env->GetStaticMethodID( cls, "intMethod", "(I)I" );
int x = 5;
jint cubed = env->CallStaticIntMethod( cls, int_method_id, x );
printf("(%i)^3 = %i\n", x, cubed );
/* Call static method to print "Hello World!" */
jmethodID print_method_id = env->GetStaticMethodID( cls, "printMethod", "()V" );
env->CallStaticVoidMethod( cls, print_method_id );
/* Attempt to instantiate `Sample' class */
jmethodID constructor_method_id = env->GetMethodID( cls, "<init>", "V(I)" );
if ( constructor_method_id != 0 )
{
jobject jobj = env->NewObject( cls, constructor_method_id );
}
else
{
printf("`Sample' constructor not found.\n");
}
return 0;
}
JavaTest MWE:
package javatest;
public class Sample
{
int myint;
public Sample(int n)
{
myint = n;
System.out.println("[JavaTest] Instantiated");
}
public static int intMethod (int n)
{
return n*n*n;
}
public static void printMethod( )
{
System.out.println("Hello World!");
}
}
输出始终为
$ ./java_test
(5)^3 = 125
Hello World!
`Sample' constructor not found.
有什么想法吗? JNI的大多数其他问题与不正确的类路径有关,但此示例具有通过静态方法判断的正确路径。
答案 0 :(得分:4)
不知道java反汇编程序,javap。运行
$ javap -s JavaTest.class
表明正确的签名是(I)V。
变化:
jmethodID constructor_method_id = env->GetMethodID( cls, "<init>", "V(I)" );
要:
jmethodID constructor_method_id = env->GetMethodID( cls, "<init>", "(I)V" );