Saturday, February 9, 2013

Declaring the Native Method On java

 Declaration of the Native Method in Fibonacci.java

public class Fibonacci {
    public static native long recursiveNative (int n); // note the ‘native’ keyword
 }

The native method is simply declared with the native keyword, and no implementation is provided in Java. The method shown above is public, but native methods can be public, protected, private, or package-private, just like any other Java method. Similarly, native methods don’t have to be static methods, and don’t have to use primitive types only. From the caller’s point of view, a native method is just like any other method. Once it is declared, you can start adding calls to this method in your Java code, and everything will compile just fine. However, if your application runs and calls Fibonacci.recursiveNative, it will crash with an UnsatisfiedLinkError exception. This is expected because you really haven’t done much so far other than declare a function, and the actual implementation of the function does not exist yet.
Once your native method is declared, you can start writing the JNI glue layer. 

No comments:

Post a Comment