Java Reference
In-Depth Information
We then use SetIntField() to set the new value back into my - custom - jo :
// Set it back into custom - jo
jenv->SetIntField (my - custom - jo, val - fid, val);
At this point, the object referenced by my - custom - jo has been modified such
that the val field has a new value. If the original Java class prints out the value
of my - custom.val , its value will have changed to 26 from the original 13.
The Web Course contains a complete working example of the code snippets
shown above in the JMIDemo.java and NativeJNIDemo.cpp files. Obvi-
ously the nesting procedure used above can be used to any depth.
22.8.4 Getting and setting static field values
with the field ID
The procedure for dealing with static fields is very nearly the same as for non-
static fields. The difference is that there is never a jobject variable in use. We
only know about the jclass . Corresponding to each GetXxxField() function
for non-static fields there is a GetStaticXxxField() function for static fields.
The GetStaticXxxField() functions take a jclass parameter instead of a
jobject . Otherwise, they are used just like the GetXxxField() functions.
Forexample, to access the static a - static - float field, we would do the
following:
jfieldID fid = jenv->GetStaticFieldID (cls,
"a - static - float", "F");
if (fid == NULL) return NULL;
jfloat a - static - float = jenv->GetStaticFloatField (cls,
fid);
Of course there are SetStaticXxxField() functions as well to set the value
of static fields.
22.9 Calling Java methods from native code
We have demonstrated how C/C
code can use the function arguments received
in the native function call and how C/C
++
code can locate, get, and set the values
of fields within Java objects and classes. It is also possible for native code to call
Java methods.
Since Java methods exist only inside of classes, it is obviously necessary to
have a reference to the class or object that contains the desired method. Also, the
method within that class must be identified somehow. Identification of the desired
method is handled with a method ID , much like a field ID is used to identify
fields. JNI has GetMethodID() and GetStaticMethodID() functions to
locate method IDs of non-static and static methods, respectively. Those functions
++
Search WWH ::




Custom Search