img
keyword, which is used to declare native code methods. Once declared, these methods can
be called from inside your Java program just as you call any other Java method.
To declare a native method, precede the method with the native modifier, but do not
define any body for the method. For example:
public native int meth() ;
After you declare a native method, you must write the native method and follow a rather
complex series of steps to link it with your Java code.
Most native methods are written in C. The mechanism used to integrate C code with a
Java program is called the Java Native Interface (JNI). A detailed description of the JNI is
beyond the scope of this topic, but the following description provides sufficient information
for most applications.
NOTE  The precise steps that you need to follow will vary between different Java environments.
OTE
They also depend on the language that you are using to implement the native method. The
following discussion assumes a Windows environment. The language used to implement the
native method is C.
The easiest way to understand the process is to work through an example. To begin, enter
the following short program, which uses a native method called test( ):
// A simple example that uses a native method.
public class NativeDemo {
int i;
public static void main(String args[]) {
NativeDemo ob = new NativeDemo();
ob.i = 10;
System.out.println("This is ob.i before the native method:" +
ob.i);
ob.test(); // call a native method
System.out.println("This is ob.i after the native method:" +
ob.i);
}
// declare native method
public native void test() ;
// load DLL that contains static method
static {
System.loadLibrary("NativeDemo");
}
}
Notice that the test( ) method is declared as native and has no body. This is the method that
we will implement in C shortly. Also notice the static block. As explained earlier in this topic, a
static block is executed only once, when your program begins execution (or, more precisely,
when its class is first loaded). In this case, it is used to load the dynamic link library that
contains the native implementation of test( ). (You will see how to create this library soon.)
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home