Thursday, 24 February 2011

1. Write the Java Code (Native Methods)

The following Java code segment defines a class named HelloWorld that has one method and a static code segment.
class HelloWorld {
public native void displayHelloWorld();

static {
System.loadLibrary("hello");
}
}

Define a Native Method

You can tell that the implementation for the HelloWorld class's displayHelloWorld() method is written in another programming language because of the native keyword that appears as part of its method definition:
public native void displayHelloWorld();
This method definition provides only the method signature for displayHelloWorld() and does not provide any implementation for it. The implementation for displayHelloWorld() is provided in a separate C language source file. The method definition for displayHelloWorld() also indicates that the method is a public instance method, accepts no arguments and returns no value. For more information about arguments to and return values from native methods see .
Like other methods, native methods must be defined within a Java class.

Load the Library

The C code that implements displayHelloWorld must be compiled into a dynamically loadable library (you will do this in Step 6: Create a Dynamically Loadable Library) and loaded into the Java class that requires it. Loading the library into the Java class maps the implementation of the native method to its definition. The following static code block from the HelloWorld class loads the appropriate library, named hello. The runtime system executes a class's static code block when it loads the class.
static {
System.loadLibrary("hello");
}
The loadLibrary() method is part of the System class.

Create the Main Program

In a separate source file, named Main.java, create a Java application that instantiates HelloWorld and calls the displayHelloWorld() native method.
class Main {
public static void main(String args[]) {
new HelloWorld().displayHelloWorld();
}
}
As you can see from the code sample above, you call a native method in the same manner as you call a regular method: just append the name of the method to the end of the object name with a period ('.'). A matched set of parentheses, ( and ), follow the method name and enclose any arguments to pass into the method. The displayHelloWorld() method doesn't take any arguments.

No comments:

Post a Comment