JNI规范中仅仅给出了String,Array两种引用类型的访问,那么如果使用了自定义的类,在JNI中该如何访问?如以下代码所示,用户自定义了Student类,创建了实例student,并希望在JNI函数中修改实例student的成员age。

package com.demo;

public class Demo {
	Student student = new Student("Jim", 15);

	public static void main(String[] args) {
		Demo d = new Demo();
		System.out.println("Before setting: " + student.toString());
		d.setStudentAge(student);
		System.out.println("After setting: " + student.toString());
	}

	native void setStudentAge(Student student);

	static {
		// Loading the dynamic link library
	}
}

class Student {
	String name;
	int age;

	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public void toString() {
		return name + ":" + age;
	}
}

对应的JNI函数:

Java_com_demo_Demo_setStudentAge(JNIEnv* env, jobject obj, jobject student)
{
	// How to access 'age' member of student ?
}

其实思路是一样的,先找到Student类,然后找到’age’的fieldID。

struct fieldIds {
	jclass studentClass;
	jfieldID name;
	jfieldID age;
}studentFieldIds;

Java_com_demo_Demo_setStudentAge(JNIEnv* env, jobject obj, jobject student)
{
	studentFieldIds.studentClass = (*env)->FindClass(env, "com/demo/Student");
	if (studentClass == NULL)
		return;

	studentFieldIds.name = (*env)->GetFieldID(env, studentFieldIds.studentClass, "name", "Ljava/lang/String;");
	studentFieldIds.age = (*env)->GetFieldID(env, studentFieldIds.studentClass, "age", "I");

	// change the 'age' value of student
	(*env)->SetIntField(env, student, studentFieldIds.age, 20);
}

相关文章:

  • 2022-12-23
  • 2021-12-03
  • 2021-09-11
  • 2022-01-18
  • 2022-12-23
  • 2021-06-14
  • 2021-07-10
  • 2021-04-06
猜你喜欢
  • 2021-12-13
  • 2021-11-11
  • 2021-09-28
  • 2021-06-25
  • 2022-12-23
  • 2021-11-01
相关资源
相似解决方案