Search code examples
javajava-native-interface

why loading JNI in java is done in static initializer?


In many examples of using JNI, I see something like:

class SampleClass {
    static {
        System.loadLibrary("somelib");
    }
    ...
}

What is the purpose of this special syntax? why using this (and not just in the class constructor or something like that?


Solution

  • I think you will get the best answer from the book:

    Java™ Native Interface: Programmer’s Guide and Specification, The

    Where you can read:

    Before the native method print can be called, the native library that implements print must be loaded. In this case, we load the native library in the static initializer of the HelloWorld class. The Java virtual machine automatically runs the static initializer before invoking any methods in the HelloWorld class, thus ensuring that the native library is loaded before the print native method is called.

    In general, nothing prevents you from loading library inside method of a class. Method, that is not static. But in that case, you have to make sure that you load library (by calling method that invokes load or loadLibrary) before you call any native method.

    Also, if you want to load another version of library, without playing with multiple ClassLoaders, you can always use wrapper code. This way, you can dynamically switch between native code implementations.

    Take a look here: dynamic loading of library in JNI