|
The native
modifier is applicable only to methods. You only need to declare
a native method in Java class which can be done by providing a method signature
followed by semicolon. The implementation is provided in native[‡‡‡‡‡‡] library. Declaring native method
is in a way similar to declaring an abstract method in as both of them do not
provide any implementation.
Programmers need native methods to handle situations in which an
application cannot be written entirely in Java. The typical situation may be
when the standard Java class library may not support the platform-dependent
features needed by the application. You may also want to implement
time-critical code in a lower-level programming language, such as assembly, and
then have the Java application call these native methods. This is usually done
to improve execution speed and performance. Generally, these situations are
faced by programmers trying to port Java onto a new platform. As an application
programmer, you would rarely need to write a native library or use native methods.
Listing 3.18 shows how a native method myNative()defined in 
the native library native.dll is declared and invoked.
The native library native.dll is loaded in static initializer. This is done just to make ensure that the library native.dll is available before the myNative() is invoked. Note that you are not required to load the library in static initializer although it is a good practice to do so.
Declaration facts for native method
Here is a quick summary of the declaration facts for native methods.
A native method cannot be declared as abstract. Abstract
method declaration implies that the subclasses should implement the method
whereas native method declaration implies that the implementation lies in
native library, not in the class’s subclasses.
When a native method is invoked, the native library containing
its implementation must be already loaded. One way of ensuring this is
to load the library in static initializer.
Native methods are invoked just like any other Java method.