這篇文章主要介紹了C語(yǔ)言訪問(wèn)JAVA的構(gòu)造方法猾担、父類方法。
訪問(wèn)構(gòu)造方法
例子://使用java.util.Date產(chǎn)生一個(gè)當(dāng)前的時(shí)間戳
java代碼:
//方法聲明
public native Date accessConstructor();
然后在main方法中調(diào)用
C代碼:
//訪問(wèn)構(gòu)造方法
JNIEXPORT jobject JNICALL Java_JniTest_accessConstructor
(JNIEnv *env, jobject jobj) {
jclass cls = (*env)->FindClass(env, "java/util/Date");
//jmethodID
jmethodID constructor_mid = (*env)->GetMethodID(env, cls, "<init>", "()V");
//實(shí)例化一個(gè)Date對(duì)象
jobject date_obj = (*env)->NewObject(env, cls, constructor_mid);
//調(diào)用getTime方法
jmethodID mid = (*env)->GetMethodID(env, cls, "getTime", "()J");
jlong time = (*env)->CallLongMethod(env, date_obj, mid);
printf("\ntime:%lld\n", time);
return date_obj;
}
訪問(wèn)父類方法
首先新建兩個(gè)類刺下,Human和Man
Human:
public class Human {
public void sayHi(){
System.out.println("人類說(shuō)你好0筻凇!");
}
}
Man:
public class Man extends Human{
@Override
public void sayHi() {
System.out.println("男人說(shuō)你好i佘浴工腋!");
}
public void sayHi2(){
super.sayHi();
}
}
在調(diào)用類中創(chuàng)建一個(gè)Human類,并用子類來(lái)實(shí)例化畅卓。
public Human human = new Man();
C代碼:
//調(diào)用父類方法
JNIEXPORT void JNICALL Java_JniTest_accessNonvirtualMethod
(JNIEnv *env, jobject jobj) {
jclass cls = (*env)->GetObjectClass(env, jobj);
//獲取man屬性(對(duì)象)
jfieldID fid = (*env)->GetFieldID(env, cls, "human", "LHuman;");
//獲取
jobject human_obj = (*env)->GetObjectField(env, jobj, fid);
//執(zhí)行sayHi方法
jclass human_cls = (*env)->FindClass(env, "Human"); //注意:傳父類的名稱
jmethodID mid = (*env)->GetMethodID(env, human_cls, "sayHi", "()V");
//執(zhí)行
(*env)->CallObjectMethod(env, human_obj, mid);
//調(diào)用的父類的方法
(*env)->CallNonvirtualObjectMethod(env, human_obj, human_cls, mid);
}