This section illustrates the "can call" Java methods from native methods. Our example program, Callbacks.java
invokes a native method. The native method then makes a call back to a Java method. To make things a little more interesting, the Java method again (recursively) calls the native method. This process continues until the recursion are five levels deep, at which time the Java method returns without making any m Ore calls to the native method. To help you see this, the Java method and the native method print a sequence of tracing information.
Calling a Java Method from Native CodeLet US focus on the implementation of
Callbacks_nativeMethod
, implemented in
Callbacks.c
. This native method contains a call back to the Java method
Callbacks.callback
.
Jniexport void Jnicalljava_callbacks_nativemethod (jnienv *env, jobject obj, jint depth) { Jclass cls = (*env) Getobjectclass (env, obj); Jmethodid mid = (*env)->getmethodid (env, CLS, "Callback", "(I) V"); if (mid = = 0) return; printf ("in C, depth =%d, about to enter java\n", depth); (*env)->callvoidmethod (env, obj, Mid, depth); printf ("in C, depth =%d, back from java\n", depth);}
You can call a instance (Non-static) method by following these three steps:
- Your Native method calls
GetObjectClass
. This returns the Java class object to which the Java object belongs.
- Your Native method then calls
GetMethodID
. This performs a lookup for the Java method in a given class. The lookup is based on the name of the method as well as the method signature. If The method does not exist, GetMethodID
returns 0. The immediate return from the native method is at a, causes a to is NoSuchMethodError
thrown in Java code.
- Lastly, your native method calls
CallVoidMethod
. This invokes an instance method, the has void
return type. You pass the object, method ID, and the actual arguments to CallVoidMethod
.
Forming the method Name and method Signature
The JNI performs a symbolic lookup based on the method ' s name and type signature. This ensures the same native method would work even after new methods has been added to the corresponding Java class.
The method name is the Java method name in UTF-8 form. Specify the method name for a constructor of a class by enclosing the word init
within angle brackets (this appears as "& Lt;init> ").
Note that the JNI uses method signatures to denote the type of Java methods. The signature (I)V
, for example, denotes a Java method, takes one argument of type and have int
return type void
. T He general form of a method signature argument is:
"(argument-types) Return-type"
The following table summarizes the encoding for the Java type signatures:
Java VM Type Signatures
Signature |
Java Type |
Z |
Boolean |
B |
Byte |
C |
Char |
S |
Short |
I |
Int |
J |
Long |
F |
Float |
D |
Double |
L Fully-qualified-class; |
Fully-qualified-class |
[Type |
Type[] |
(arg-types) Ret-type |
Method type |
For example, the Prompt.getLine
method has the signature:
(ljava/lang/string;) ljava/lang/string;
Whereas the
Callbacks.main
Method has the signature:
([ljava/lang/string;) V
Array types is indicated by a leading square bracket ([) followed by the type of the array elements.
Using
javap
To Generate Method Signatures
To eliminate the mistakes in deriving method signatures by hand, you can use the tool-to- javap
print out method signatures . For example, by running:
Javap-s-P Prompt
You can obtain the following output:
Compiled from Prompt.javaclass Prompt extends Java.lang.Object /* acc_super bit set */{ private native GetLine (Lj ava/lang/string;) ljava/lang/string; public static main ([ljava/lang/string;) v <init> () v Static <clinit> () v}
The "-S" flag informs to javap
output signatures rather than normal Java types. The "-p" flag causes private members to be included.
Calling Java Methods Using Method IDs
In JNI, you pass the method ID to the actual method invocation function. This makes it possible to first obtain the method ID, which was a relatively expensive operation, and then use the method I D many times at later points to invoke the same method.
It is important to keep in mind that a method ID was valid only as long as the class from which it is derived are not UN Loaded. Once The class is unloaded, the method ID becomes invalid. So if you want to cache the method ID, make sure to keep a live reference to the Java class from which the method ID is de Rived. jclass
as long as the reference to the Java class (the value) exists, the native code keeps a live reference to the class. The section Local and Global References explains-keep a live reference even after the native method returns and the jclass
value goes out of scope.
Passing Arguments to Java Methods
The JNI provides several ways to pass arguments to a Java method. Most often, you pass the arguments following the method ID. There is also, variations of method invocation functions that take arguments in an alternative format. For example, the CallVoidMethodV
function receives the arguments with a va_list
, and the CallVoidMethodA
function expects the arguments in an array of jvalue
Union types:
typedef Union JVALUE { Jboolean z; Jbyte B; Jchar C; Jshort S; Jint i; Jlong J; Jfloat F; Jdouble D; Jobject l;} jvalue;
Besides CallVoidMethod
function, the JNI also supports instance method invocation functions with other return types, such as CallBooleanMethod
, CallIntMethod
, and so on. The return type of the method invocation function must match with the Java method you wish to invoke.
Calling static methodsyou can call Static Java method from your native code by following these steps:
- Obtain the method ID using
GetStaticMethodID
, as opposed to GetMethodID
.
- Pass the class, method ID, and arguments to the family of static method invocation functions:
CallStaticVoidMethod
, CallStaticBooleanMethod
, and so on.
If you compare instance method invocation functions to static method invocation functions, you'll notice that instance m Ethod invocation functions receive the
Object, rather than the class, as the second argument following the JNIEnv argument. For example, if we add a static method
static int incdepth (int depth) {return depth + 1};
Into
Callback.java
, we can call it from
Java_Callback_nativeMethod
Using
Jniexport void Jnicalljava_callbacks_nativemethod (jnienv *env, jobject obj, jint depth) { Jclass cls = (*env) Getobjectclass (env, obj); Jmethodid mid = (*env)->getstaticmethodid (env, CLS, "Incdepth", "(i) I"); if (mid = = 0) return; depth = (*env)->callstaticintmethod (env, CLS, Mid, depth);
Calling Instance Methods of a superclassyou can call Instance Methods defined in a superclass that has been overridden in The class to which the object belongs. The JNI provides a set of
CallNonvirtual<type>Method
Functions for this purpose. To call instance methods from the superclass that defined them, your do the following:
- Obtain the method ID from the superclass using
GetMethodID
, as opposed to GetStaticMethodID)
.
- Pass the object, superclass, method Id, and arguments to the family of nonvirtual invocation functions:
CallNonvirtualVoidMethod
, CallNonvirtualBooleanMethod
, and So on.
It is rare so you'll need to invoke the instance methods of a superclass. This facility was similar to calling a superclass method, say
f
, using:
SUPER.F ();
In Java.