Saturday, April 14, 2012

Native Modifier

The native Modifier : In java applications, sometimes we will want to use a method that exists outside the JVM. In this scenario, the native modifier can help, native modifier can only apply to a method. Just as the abstract keyword, the native keyword indicates that the implementation of the method exists elsewhere. In case of abstract, the implementation of a method may exist in a subclass of the class in which the abstract method is declared. 

But in the case of native, the implementation of the method exists in a library outside the JVM. The native method is usually implemented in a non-Java language such as C or C++. Before a native method can be invoked, a library that contains the method must be loaded and that library is loaded by making the following system call:

System.loadLibrary("libraryName");

To declare a native method, precede the method with the native modifier, but do not define any body for the method. For example:

public native  void Nativemethod() ;

After you declare a native method, you must write the native method and follow a complex series of steps to link it with your Java code. For example, the following code fragment presents an example of loading a library named NativeMethodDef which contains a method named NativeMethod():


Java Tutorialslass NativeModifierExample
 {
       native void NativeMethod();
       static 
     {
            System.loadLibrary("NativeMethodDef");
           }
     }
Note that the library is loaded in a static code block which suggest that the library is loaded at the class load time, so it is there when a call to the native method is made. One can use the native method in the same way as we use a non-native method. For example, the following two lines of code would invoke the native method,

NativeModifierExample obj = new NativeModifierExample();
obj.NativeMethod();

No comments:

Post a Comment