Loading native libraries

suggest change

The common idiom for loading shared library files in Java is the following :

public class ClassWithNativeMethods {
    static {
        System.loadLibrary("Example");
    }

    public native void someNativeMethod(String arg);
    ...

Calls to System.loadLibrary are almost always static so as to occur during class loading, ensuring that no native method can execute before the shared library has been loaded. However the following is possible :

public class ClassWithNativeMethods {
    // Call this before using any native method
    public static void prepareNativeMethods() {
        System.loadLibrary("Example");
    }

    ...

This allows to defer shared library loading until necessary, but requires extra care to avoid java.lang.UnsatisfiedLinkErrors.

Target file lookup

Shared library files are searched for in the paths defined by the java.library.path system property, which can be overriden using the -Djava.library.path= JVM argument at runtime :

java -Djava.library.path=path/to/lib/:path/to/other/lib MainClassWithNativeMethods

Watch out for system path separators : for example, Windows uses ; instead of :.

Note that System.loadLibrary resolves library filenames in a platform-dependent manner : the code snippet above expects a file named libExample.so on Linux, and Example.dll on Windows.

An alternative to System.loadLibrary is System.load(String), which takes the full path to a shared library file, circumventing the java.library.path lookup :

public class ClassWithNativeMethods {
    static {
        System.load("/path/to/lib/libExample.so");
    }

    ...

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Java Native Interface (JNI):
* Loading native libraries

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
36 Java Native Interface (JNI)
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap