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)?
Asked
Active
Viewed 1.4k times
3 Answers
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
-
2This 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
-
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
-
2looks 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