Getting a reference to a super class.

Suppose I have:

* a class named Base which contains a function named foo().

* a class named Derived which extends Base that also has a function foo().

I'd like to call Base::foo() using JNI (this is me playing around getting to know JNI; I know this isn't terribly useful).

In Derived, I defined:

publicnativevoid nativeMethod();

The first step is to get a class reference for Base.So I do this:

JNIEXPORTvoid JNICALL

Java_Derived_nativeMethod(JNIEnv *env, jobject obj)

{

jclass cls = env->GetObjectClass(obj);

jmethodID mid = env->GetMethodID(cls,"foo","()V");

if ( mid == NULL )return;

env->CallVoidMethod(cls, mid);

}

But there's already a problem. Since nativeMethod() is called from within Derived::main(), the jobject that's passed to nativeMethod() is an instance of a Derived object, not the Base object.So Derived::foo() will be called, not Base::foo().

How do I get a reference to the super class in order to run Base::foo()?

Thanks!

[1372 byte] By [628015caffeinea] at [2007-11-26 12:18:46]
# 1

Got it.

#include <jni.h>

#include <iostream>

#include "CallSuperClass.h"

using namespace std;

JNIEXPORT void JNICALL

Java_Derived_nativeMethod(JNIEnv *env, jobject obj)

{

jclass cls = env->FindClass("Base");

jmethodID mid = env->GetMethodID(cls, "foo", "()V");

if ( mid == NULL ) return;

cout << endl << endl << "C:About to call Base::foo..." << endl;

env->CallNonvirtualVoidMethod(obj, cls, mid);

cout << "C:It's been called!" << endl << endl;

}

628015caffeinea at 2007-7-7 14:58:57 > top of Java-index,Archived Forums,Socket Programming...