Of course, the main problem with using native methods is that they make your Java code applet-unfriendly and non-portable; in effect, you lose the very features that make Java such an interesting and important language in today's network-centric computing environments. In many situations, the best option may simply be to forget about Java and develop your application in a language better suited to the problem domain. If you need to use Java, however, it is possible to use native methods in classes without sacrificing portability, through the use of fallbacks.
The basic idea is this: For each native method in your class, you supply an equivalent non-native method that will be executed if the system cannot locate or load the dynamic library containing the native method code.
Your class will obviously need some means of registering whether native methods are available, and this can be done by using a boolean class variable. This variable is set to true or false in the static block of code that attempts to load the dynamic library associated with your class:
public class Convolver {
private static boolean _native;
static {
try {
System.err.println("Convolver: loading dynamic library...");
System.loadLibrary("Convolver");
_native = true;
}
catch (UnsatisfiedLinkError e) {
System.err.println("Convolver: no library found - " +
"using fallback methods...");
_native = false;
} catch (Exception e) {
System.err.println("Convolver: cannot load library - " +
"using fallback methods...");
_native = false;
}
}
...
}
In the above example, _native is used to flag the availability (or lack) of native methods. It is set to true if the call to System.loadLibrary succeeds. If, however, the named library cannot be found -- because the library does not exist on the user's system, or because
LD_LIBRARY_PATH or its equivalent is not set correctly -- then an UnsatisfiedLinkError is thrown. We catch this and set _native to false (and also print a warning to the user that fallbacks will be used instead of native methods).
The second catch block in the above example makes our class applet-friendly, because it allows us to recover from exceptions thrown by a Web
browser whose security manager prohibits the use of dynamic libraries. Again, we print a warning message on stream System.err and set _native to false.
Note that class users should not be allowed to invoke native methods and their associated fallback methods directly; it is up to the class itself to decide, when it is loaded into memory, whether to use native or fallback code. Consequently, we make the native methods and their fallbacks private and supply a public method that simply invokes the native method or the fallback, depending on the value of our boolean class variable: