Java Reference
In-Depth Information
Table 22.2
JNI functions to get Java field values.
Java field type
JNI function
Return type
boolean
GetBooleanField()
jboolean
byte
GetByteField()
jbyte
char
GetCharField()
jchar
short
GetShortField()
jshort
int
GetIntField()
jint
long
GetLongField()
jlong
float
GetFloatField()
jfloat
double
GetDoubleField()
jdouble
22.8.3 Getting and setting non-static field values
with the field ID
Getting the field ID is only half the battle, since what we really want is the field
itself. With a field ID in hand, we can then get and set the values of static fields
in a class or non-static fields in an object. We discuss non-static fields first. Let
us consider the
some
-
int
field of our
JNIDemo
class. Since it is an
int
,we
get its value with the
GetIntField()
method:
jint my
-
int = jenv->GetIntField (jo, some
-
int
-
fid);
The
jo
parameter is a reference to the object that contains the desired field.
Since there may be multiple object instantiations, each with different values for
the fields, we must pass in a reference to the object that we're interested in.
GetIntField()
also requires the field ID of the field we desire. Here we have
used the
some
-
int
-
fid
obtained earlier in Section 22.8.1. There are analogous
GetXxxField()
functions for the other primitives as shown in Table 22.2. Each
“
Get
„
method takes a
jobject
parameter, which must not be
NULL
, and a valid
field ID. Each returns a corresponding
“
j
„
data type to the C side as shown in
the table.
To set the value of a primitive field, we use the field ID and a
“
Set
„
method.
Forexample, if we want to change the value of the
JNIDemo.some
-
int
field
from a native method implementation, we use code like the following:
jint new
-
value
=
7;
jenv-
>
SetIntField (jo, some
-
int
-
fid, new
-
value);
There are, of course,
“
Set
„
methods for each primitive type.
These built-in JNI methods handle all the Java primitive types. For object
types, there are general
GetObjectField()
and
SetObjectField()
func-
tions. They apply for standard objects, like the
some
-
string String
field of
JNIDemo
, and for any custom objects the programmer might define. The return
Search WWH ::
Custom Search