Java Reference
In-Depth Information
the non-static versions only in that they require a jclass reference to the class
in which the static method resides rather than a jobject reference.
For each CallXxxMethod() function there are two additional functions
available that utilize different mechanisms for passing parameters to the Java
methods they call. The CallXxxMethodV() family of functions pass the param-
eters in an argument of type va - list , and the CallXxxMethodA() family
of functions pass the parameters in an array of jvalues .Type va - list is
a special type used within the C/C
language to pass a variable number of
arguments. The printf family of functions is a well-known example using a
variable number of arguments. Type jvalue is defined as a union in jni.h .In
general, the plain functions are the easiest to use. Readers familiar with C/C
++
++
unions and va - list arguments might find the A and V styles useful. The
CallXxxStaticMethod() functions exist in A and V styles as well.
22.9.3 Finding classes
In the examples above, we assumed that the jclass identifying the class con-
taining the desired method was already available. In practice, we must often
first obtain the jclass for the desired class. Suppose, for example, that we
would like to call a method on the Java String class. We first need a jclass
for java.lang.String so we can find the required method ID. The JNI
FindClass() function serves that purpose, and using it is quite simple.
FindClass() takes a fully qualified name of a class and searches the
CLASSPATH to find, and load if necessary, the named class. To find the jclass
for java.lang.String class, we use
jclass cls = jenv->FindClass ("java/lang/String");
As usual, we need to check for a NULL return in case of exceptions, the most
likely being NoClassDefFoundError . FindClass() can find the jclass
for any class on the CLASSPATH , not just Java system classes.
22.10 Exceptions in JNI
We already briefly touched upon Java exceptions in the discussions above. In
those cases, the JNI system itself was responsible for raising the exception due
to unexpected events such as memory allocation errors or the inability to find
field or method IDs. We discuss these system-generated exceptions below. (For
simplicity, we refer to all these exceptional conditions as exceptions rather than
distinguishing between exceptions and errors.) It is also possible for custom
code that you write to throw and catch Java exceptions. We describe throwing
and catching your own exceptions after we discuss exceptions raised by the JNI
system in more detail. In all cases, if an exception is not handled within native
code, it eventually propagates back to the JVM once the native code returns.
Search WWH ::




Custom Search