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 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 C language source file. The method definition fordisplayHelloWorld()
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 implementsdisplayHelloWorld
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 theHelloWorld
class loads the appropriate library, namedhello
. The runtime system executes a class's static code block when it loads the class.
Thestatic { System.loadLibrary("hello"); }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 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.
No comments:
Post a Comment