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.UnsatisfiedLinkError
s.
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");
}
...