Java Reference
In-Depth Information
Object variables that your native code may modify should carry the
volatile
modifier. The
file
HelloJni.java
, shown in
Example 24-9
, is a good starting point.
Example 24-9. HelloJni.java
/**
* A trivial class to show Java Native Interface 1.1 usage from Java.
*/
public
public class
class
HelloJni
HelloJni
{
int
int
myNumber
=
42
;
// used to show argument passing
// declare native class
public
public native
native
void
void
displayHelloJni
();
// Application main, call its display method
public
public static
void
main
(
String
[]
args
) {
System
.
out
.
println
(
"HelloJni starting; args.length="
+
args
.
length
+
"..."
);
static
void
for
for
(
int
int
i
=
0
;
i
<
args
.
length
;
i
++)
System
.
out
.
println
(
"args["
+
i
+
"]="
+
args
[
i
]);
HelloJni hw
=
new
new
HelloJni
();
hw
.
displayHelloJni
();
// call the native function
System
.
out
.
println
(
"Back in Java, \"myNumber\" now "
+
hw
.
myNumber
);
}
// Static code blocks are executed once, when class file is loaded
static
static
{
System
.
loadLibrary
(
"hello"
);
}
}
The second step is simple; just use
javac HelloJni.java
as you normally would. You probably
won't get any compilation errors on a simple program like this; if you do, correct them and
try the compilation again.
Next, you need to create an
.h
file. Use
javah
to produce this file:
// produces HelloJni.h
javah jni.HelloJni
The
.h
file produced is a “glue” file, not really meant for human consumption and particu-
larly not for editing. But by inspecting the resulting
.h
file, you'll see that the C method's
name is composed of the name
Java
, the package name (if any), the class name, and the
method name: