Java Reference
In-Depth Information
and jthrowable , all other Java objects appear on the C side as jobject data
types.
AJava object has both state and behavior, or data and methods, and JNI must
provide a way to gain access to the data inside an object for manipulation on
the C side. In addition, JNI also makes it possible to make method calls to the
methods in a Java object. Said another way, not only can Java call C/C
++
code
using JNI, but C/C
code can also call Java code using JNI. We look first at
accessing the data fields within an object.
++
22.8.1 The field ID
JNI provides a way for the native language programmer to get and set the values
of member variables inside a Java object or class. Both class (static) and instance
variables are available. On the Java side, a member variable, also known as a field ,
is identified by its name using the object.field - name syntax. As might be
imagined, things are not so simple on the native side. Like everything else in JNI,
the getting and setting of fields is done through the use of JNI functions. Doing
so is a two-step procedure. First, you must obtain an identifier for the desired
field within the Java class. This identifier then serves as a kind of index used to
locate the member variable within the class or object.
The identifier is called the field ID and is of type jfieldID .Java fields can
be of any type, and it is necessary to know both the field name and type signature
in the Java class to obtain the corresponding field ID. Once the field ID is had, it is
used to get or set the value of the corresponding field. JNI factors out the process
of obtaining the field IDs from the process of getting and setting the actual field
values so that the field IDs do not have to be recalculated each time they are used,
saving time when the same field is accessed multiple times.
Field IDs are obtained with the GetFieldID() and GetStaticField-
ID() functions as illustrated here:
jfieldID fid = jenv- > GetFieldID (cls, < field-name > ,
< type-signature > );
if (fid == NULL)
return NULL;
where < field-name > is a C string naming the desired field, < type-
signature > is a C string containing the type signature, and cls is an argument
of type jclass that identifies the class the desired field is found in. We explain
the cls argument in more detail shortly.
As usual, we check for a NULL return in case of any errors. The exceptional
conditions that can be thrown by GetFieldID() are NoSuchFieldError ,
ExceptionInInitializerError , and OutOfMemoryError . The most
common is NoSuchFieldError , usually due to a misspelled < field-name >
or incorrect < type-signature > , both of which must be exactly correct. A
Search WWH ::




Custom Search