The JNI provides functions that native methods use to get and set Java member variables. You can get and set both instance and class member variables. Similar to accessing methods, you use one set of JNI functions to access instance member variables and another set of JNI functions to access class member variables.
Our example program,
To get and set Java member variables from a native language method, you must do the following:
Specify member variable signatures following the same
encoding scheme as method signatures. The general form of a member variable
signature is:
"member variable type
The member variable signature is the encoded symbol for the type of the
member variable, enclosed in double quotes (). The member variable symbols are the same
as the argument symbol
Bhopal newsFieldAccess.javasourceIcon (in a .java source file), contains a
class with one class integer member variable si and an instance
string member variable s. The example program calls the native method
accessFields, which prints out the value of these two
member variables and then sets the member variables to new values. To verify the member variables
have indeed changed, we print out their values again in the Java application after
returning from the native method.
Procedure for Accessing a Java Member Variable
Just as we did when calling a Java method, we factor out the cost of member variable lookup
using a two-step process. First we obtain the member variable ID, then use the member variable ID to access the member variable itself. The member variable ID uniquely identifies a member variable in
a given class. Similar to method IDs, a member variable ID remains valid until
the class from which it is derived is unloaded.
FieldAccess.c, we get the identifier for the class integer member variable si as follows:
fid = (*env)->GetStaticFieldID(env, cls, "si, "I);
and we get the identifier for the instance string member variable s as follows:
fid = (*env)->GetFieldID(env, cls, "s, "Ljava/lang/String;);
FieldAccess.c, we use GetStaticIntField to get the value of the class integer member variable si, as follows:
si = (*env)->GetStaticIntField(env, cls, fid);
We use the function GetObjectField to get the value of the instance string member variable s:
jstr = (*env)->GetObjectField(env, obj, fid);
Member Variable Signatures
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100