Step By Step |
The following Java code segment defines a class namedHelloWorld
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 theHelloWorld
class'sdisplayHelloWorld()
method is written in another programming language because of thenative
keyword that appears as part of its method definition:This method definition provides only the method signature forpublic native void displayHelloWorld();displayHelloWorld()
and does not provide any implementation for it. The implementation fordisplayHelloWorld()
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 .Like other methods, native methods must be defined within a Java class.
Load the Library
The native language code that implementsdisplayHelloWorld
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, namedhello
. The runtime system executes a class's static code block when it loads the class.Loading Dynamic Librariescontains more information about usingstatic { System.loadLibrary("hello"); }loadLibrary()
to load dynamic libraries.Create the Main Program
In a separate source file, named Main.java, create a Java application that instantiatesHelloWorld
and calls thedisplayHelloWorld()
native method.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. Theclass Main { public static void main(String[] args) { new HelloWorld().displayHelloWorld(); } }displayHelloWorld()
method doesn't take any arguments.
Step By Step |