Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Step By Step


Step 1: Write the Java Code

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 native 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 Implementing Native Methods(in the Using the JNI to Integrate Native Code and Java Programs trail).

Like other methods, native methods must be defined within a Java class.

Load the Library

The native language code that implements displayHelloWorld must be compiled into a shared library (you will do this in Step 6: Create a Shared 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");
}

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.


Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Step By Step