Father.java代码
package com.easou.abo.jnitest; public class Father { public void function(){ System.out.println("Father::function"); } }
Child.java代码
package com.easou.abo.jnitest; public class Child extends Father { public void function(){ System.out.println("Child::function"); } }
Demo.java代码
package com.easou.abo.jnitest; public class Demo { public int number = 10; public native void test(); public Father p = new Child(); public static void main(String[] args) { System.loadLibrary("testJni"); Demo dm = new Demo(); dm.test(); } }
C代码
#include "com_easou_abo_jnitest_Demo.h" #include <stdio.h> #include<iostream> using namespace std; JNIEXPORT void JNICALL Java_com_easou_abo_jnitest_Demo_test(JNIEnv * env, jobject obj){ jclass hello_clazz = env->GetObjectClass(obj);//获得java中的类 jfieldID id_p = env->GetFieldID(hello_clazz,"p","Lcom/easou/abo/jnitest/Father;"); jobject p = env->GetObjectField(obj,id_p); jclass clazz_Father = env->FindClass("com/easou/abo/jnitest/Father"); jmethodID id_Father_function = env->GetMethodID(clazz_Father,"function","()V"); env->CallVoidMethod(p,id_Father_function);//子类 env->CallNonvirtualVoidMethod(p,clazz_Father,id_Father_function);//父类 }
控制台输出
Child::function
Father::function