Search code examples
javajava-native-interfacejava.library.path

Load Native Library from Class path


I have a project setup that follows the Standard Directory Layout (not using Maven though):

src/main
      | java
      | resources
         | library.dll

Native DLLs are located in the resources folder and sources in the java folder. The resources folder is a member of the Java class path.

I would now like to load a DLL without having to set the JRE -Djava.library.path option or setting the PATH variable so the resulting jar file can be started with a simple double click.

Is it possible to add the resource folder to the library search path without having to do additional configuration when running the jar file? E.g. with a setting similar to the Class-Path in the Manifest?


Solution

  • There is an old-time hack that still works as of today ( 1.7.0_55 & 1.8.0_05 ) to allow you to do to a runtime update using System.setProperty() and have the JVM notice the change. In general, you do the following:

    System.setProperty("java.library.path", yourPath);
    Field sysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
    sysPath.setAccessible( true );
    sysPath.set( null, null );
    System.loadLibrary(libraryName);
    

    Google java sys_paths and look for articles about this technique.

    Take care to handle errors/exceptions. Restore original paths as needed.