本文共 2415 字,大约阅读时间需要 8 分钟。
与域一样,Java中有两类方法:实例方法和静态方法。JNI提供访问两类方法的函数,例如:
public class JavaClass {// 实例方法private String instanceMethod(){return "Instance Method";}// 静态方法private static String staticMethod(){return "StaticMethod";}}
JNI提供了用方法ID访问两类方法的途径,可以用给定实例的class对象获得方法ID。用GetMethodID函数获得实例方法的方法ID,例如:
jmethodID instanceMethodId;instanceMethodId = (*env)->GetMethodID(env,clazz,"instanceMethod","()Ljava/lang/String;");
用GetStaticMethodID函数获得静态域的方法ID,例如:
jmethodID staticMethodId;staticMethodId = (*env)->GetStaticMethodID(env,clazz,"staticMethod","()Ljava/lang/String;");
两个函数的最后一个参数均表示方法描述符,在Java中表示方法签名。
可以以方法ID为参数通过CallMethod类函数调用实际的实例方法,例如:
1、调用实例方法
jstring instanceMethodResult;instanceMethodResult = (*env)->CallStringMethod(env,instance,"instanceMethodId");
2、调用静态方法
jstring staticMethodResult;staticMethodResult = (*env)->CallStaticStringMethod(env,clazz,"staticMethodId");
HelloJni.java
public class HelloJni extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); callJavaStaticMethod(); } public native String callJavaStaticMethod(); static { System.loadLibrary("hello-jni"); } // 静态方法 private static String staticMethod() { return "StaticMethod Castiel"; }}
hellojni.c
#include#include #include JNIEXPORT void JNICALLJava_com_example_hellojni_HelloJni_callJavaStaticMethod(JNIEnv *env, jclass type) { jclass jniClass = (*env)->FindClass(env, "com/example/hellojni/HelloJni"); if (NULL == jniClass) { __android_log_print(ANDROID_LOG_INFO,"HelloJni","can't find jclass"); return; } jmethodID getMId = (*env)->GetStaticMethodID(env, jniClass, "staticMethod", "()Ljava/lang/String;"); if (NULL == getMId) { __android_log_print(ANDROID_LOG_INFO,"HelloJni","can't find method getStringFromStatic from JniClass"); return; } jstring result = (*env)->CallStaticObjectMethod(env, jniClass, getMId); const char *resultChar = (*env)->GetStringUTFChars(env, result, NULL); (*env)->DeleteLocalRef(env, jniClass); (*env)->DeleteLocalRef(env, result); __android_log_print(ANDROID_LOG_INFO,"HelloJni",resultChar);}
编译后执行程序,可以看到日志中成功打印了我们获取的Java方法:StaticMethod Castiel。
转载地址:http://zouhj.baihongyu.com/