代码改变世界

JNI系列(4):如何访问自定义类对象

2010-10-21 13:51  RayLee  阅读(3743)  评论(0编辑  收藏  举报

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);
}