8

I am looking to set the VM argument Djava.library.path programmatically. If this can't be done, what are the alternatives (if there are any)?

Jire
  • 9,680
  • 14
  • 52
  • 87
  • 2
    Possible duplicate: http://stackoverflow.com/questions/5565356/java-attach-api-changing-java-library-path-dynamically – Fls'Zen Apr 12 '13 at 01:11

3 Answers3

11

The solution is easy with this method:

public static void addLibraryPath(String pathToAdd) throws Exception {
    Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
    usrPathsField.setAccessible(true);

    String[] paths = (String[]) usrPathsField.get(null);

    for (String path : paths)
        if (path.equals(pathToAdd))
            return;

    String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
    newPaths[newPaths.length - 1] = pathToAdd;
    usrPathsField.set(null, newPaths);
}
Jire
  • 9,680
  • 14
  • 52
  • 87
  • 2
    This is a nice hack, if some 3rd-party library uses System.loadLibrary(...), which you cannot change yourself! Ty! – Stefan Jan 30 '19 at 14:05
  • Nice for JDK8, but did you already find out how to port this to JDK17? – Daniel May 07 '23 at 12:31
4

take a look at this java doc http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#setProperty(java.lang.String, java.lang.String)

you want to call the setProperty(String, String) method.

so it would look something like this in your case

System.setProperty("java.library.path","value_you_want");
Connr
  • 408
  • 6
  • 10
  • 2
    looks like you are correct for that system property as it is only read once at startup. http://fahdshariff.blogspot.jp/2011/08/changing-java-library-path-at-runtime.html – Connr Apr 12 '13 at 12:40
3

java.library.path is used when you load a dynamic library with System.loadLibrary(String libname). System.load(String filename) uses full file name and does not need java.library.path.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275