Search code examples
javainheritancejava-native-interface

Java use base class for inherited native method


If I have

public class Foo {
  static {
    System.loadLibrary("foo");
  }
  private native void foo();
}

and then

public class Bar extends Foo {
}

and in my JNI I have:

JNIEXPORT void JNICALL
org_mikesolomon_soq_Bar_foo
  (JNIEnv *env, jobject obj)
{
}

will the function foo automatically become part of Bar, or will the compiler expect a definition of foo as a native method in Bar? I'm asking because I have a bunch of classes that are inheriting from a bass class and implementing a native method in the form of:

org_mikesolomon_soq_A_foo
org_mikesolomon_soq_B_foo
org_mikesolomon_soq_C_foo
org_mikesolomon_soq_D_foo

where A, B, C and D all inherit from a base class. That would save me from writing out

public native void foo();

in each class.


Solution

  • The native method is defined in Foo. Providing an implementation in Bar doesn't make any sense, unless there is a corresponding overriding native method declaration in the Java code of Bar.

    It isn't clear what exactly you are trying to do, but this won't do anything. The native method will be ignored unless it corresponds to a Java native method declaration.