Java Reference
In-Depth Information
from
GetObjectField()
is a
jobject
,which could be cast into a
jstring
,
if appropriate.
For most objects, including all custom objects, there is no built-in
“
j
„
type to
cast to. The only way to handle such objects is a nesting of the above procedure.
We give a short example here using the
MyCustomObject
type in the
JNIDemo
class. Let's define a very simple
MyCustomObject
class that contains only one
int
field, initialized to the value 13 (the constructor is implied):
class MyCustomObject {
int val = 13;
}
Recall that the
my
-
custom
field of
JNIDemo
is a
MyCustomObject
type. If
jo
is a
jobject
reference to an instance of
JNIDemo
, then we first need to find
a
jclass
for
JNIDemo
:
// Find the jclass corresponding to the jobject
jclass cls = jenv->GetObjectClass (jo);
Then we need the field ID of the
my
-
custom
field of
JNIDemo
:
// Find the field ID of the 'my
-
custom' field
jfieldID my
-
custom
-
fid = jenv->GetFieldID (
cls, "my
-
custom", "Ljavatech/jni22/MyCustomObject;"
);
With the field ID in hand, we can get a
jobject
reference to the
my
-
custom
object:
// Get the jobject reference to 'my
-
custom'
jobject my
-
custom
-
jo = jenv->GetObjectField (jo,
my
-
custom
-
fid);
About the only meaningful thing we can do with this
jobject
is use it to look
into the
MyCustomObject
class. First, we get the corresponding
jclass
and
then get the field ID of the
val
field:
// Find the field ID of the
'
val
'
field of MyCustomObject.
jclass my
-
custom
-
cls = jenv->GetObjectClass (my
-
custom
-
jo);
jfieldID val
-
fid = jenv->GetFieldID (my
-
custom
-
cls, "val", "I");
Now we can obtain the value of the
val
field itself:
// Get the
'
val
'
field
jint val
=
jenv-
>
GetIntField (my
-
custom
-
jo, val
-
fid);
and manipulate it somehow:
// Manipulate it somehow
val *
=
2;
Search WWH ::
Custom Search