Thursday, July 3, 2014

Setting "java.library.path" programmatically

Requirement:

I have 6 dll files in my eclipse plug-in under lib/win64 folder. I wanted to load them dynamically during the launch of eclipse.

I have tried the eclipse way of bundling native-code in the plugin manifest, but somehow i could not achieve. So I have to go by manipulating the system path.

Eclipse bundle-native code mechanism:
http://blog.vogella.com/2010/07/27/osgi/


try {
     //eclipse call
Bundle bundle= getBundle();
URL fileUrl = FileLocator.toFileURL(FileLocator.find(bundle, new Path("/"), null));
String location = fileUrl.getFile();
String libPath = location + "lib/win64";
File file = new File(libPath);
System.out.println(file.getAbsolutePath());
System.setProperty("java.library.path", file.getAbsolutePath());
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


The Classloader has a static field (sys_paths) that contains the paths. If that field is set to null, it is initialized automatically. Therefore forcing that field to null will result into the reevaluation of the library path as soon as loadLibrary() is called

Resources:
http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/
http://fahdshariff.blogspot.in/2011/08/changing-java-library-path-at-runtime.html

No comments:

Post a Comment