JNI access domain, call java method

Java has two types of fields: instance fields and static fields

JNI provides functions for accessing two types of fields

java class with static field and instance field

public class JavaClass{
//实例域
private String instanceFiled = "Instance Field";
//静态域
private static String staticField = "Static Field";

}

1 Get the domain ID

JNI provides a method to access two types of domains by domain ID. You can obtain the domain ID through a given instance class object, and use the GetObjectClass function to obtain the class object.

//用对象引用获取类
jclass clazz;
clazz = (*env)->GetObjectClass(env, instance);
//获取实例域的域ID
jfieldID instanceField;
instanceField = (*env)->GetField(env,clazz, "instanceField", "Ljava/lang/String");
//获取静态域的ID
jfieldID staticFieldId;
staticFieldId = (*env)->GetStaticField(env,clazz, "staticField", "Ljava/lang/String");

Second, get the domain

After obtaining the field ID, the actual instance field can be obtained with the GetField function

//获取实例域
jstring instanceField;
instanceField = (*env)->GetObjectField(env, instance, instanceFieldID);
//获取静态域
jstring staticField;
staticField = (*env)->GetStaticObjectField(env,clazz,staticFieldId);
//在内存溢出的情况下,这些函数均返回NULL,原生代码不会继续执行

call method

java class

public class JavaClass{
//实例方法
private String instanceMethod(){
  return "instance Methid";
 }
//静态方法
private static String staticMethod(){
 return "Static Method";
 }
}

1 Get the method ID

//获取实例方法的ID
jmethod instanceMethodID;
instanceMethodId = (*env)->GetMethod(env, clazz, "instanceMehtod", "()Ljava/lang/String;");
//获取静态方法的ID
jmethodID staticMethodId;
staticMethodId = (*env)->GetStaticMethod(env, clazz, "staticMethod", "()Ljava/lang/String;");

2. Call the method according to the ID

//调用实例方法
jstring instanceMethodResult;
instanceMethodResult = (*env)->CallStringMethod(env,instacne, instanceMethod);
//调用静态方法
jstring staticMethodResult;
staticMethodResult = (*env)->CallStaticStringMethod(env, clazz, staticMethodId)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325577407&siteId=291194637