In my project I need to configure java.library.path at runtime. Does Java gives me such ability?
Asked
Active
Viewed 1,565 times
1 Answers
-1
First option is to set java.library.path to different value
/**
* Sets the java library path to the specified path
*
* @param path the new library path
* @throws Exception
*/
public static void setLibraryPath(String path) throws Exception {
System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
The second option is to append your path to java.library.path
/**
* Adds the specified path to the java library path
*
* @param pathToAdd the path to add
* @throws Exception
*/
public static void addLibraryPath(String pathToAdd) throws Exception{
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
//get array of paths
final String[] paths = (String[])usrPathsField.get(null);
//check if the path to add is already present
for(String path : paths) {
if(path.equals(pathToAdd)) {
return;
}
}
//add the new path
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length-1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
Taken from fahd.blog

Dmitry Kolesnikovich
- 669
- 2
- 15
- 33
-
2Why posting a question and an answer at the same time? If this solves your problem, please simply remove your question. – sina72 May 23 '14 at 08:44
-
Better ask why StackOverflow gives such possibility to answer my question myself :) – Dmitry Kolesnikovich May 23 '14 at 09:51