After a loooong looooong time, this is a pure technical post with CODE written in it 😉

In this post, I have mentioned about java.library.path. This is the path where the jvm searches for so/dll files when you do a System.loadLibrary(“LIBRARY”);

When I was writing that post, somewhere I read that we cannot change the “java.library.path” directly. Being an INTELLIGENT programmer, I tried to change the java.library.path property using System.setProperty(“java.library.path”). When I read the property, and got the value that I had set. I thought, those guys where INTELLIGENT. But, when I ran my application I realized that I am actually INTELLIGENT. 😀 It was not looking for the libraries that I have given in that property.

Recently, I was googling for an issue and found the following code. This code actually modifies the “java.library.path”.

public static void addDirToJavaLibraryPath(String path) 
throws IllegalAccessException, NoSuchFieldException
{
    if (path == null || path.trim().length() == 0)
    {
	return;
    }
    try
    {
	Field field = ClassLoader.class.getDeclaredField("usr_paths");
	field.setAccessible(true);
	String[] paths = (String[]) field.get(null);
	for (int i = 0; i < paths.length; i++)
	{
            // If path is already included
   	    if (path.equals(paths[i]))
	    {
		return;
	    }
	}
        // This is where we change the path
	String[] tmp = new String[paths.length + 1];
	tmp[0] = path;
	System.arraycopy(paths, 0, tmp, 1, paths.length);
	field.set(null, tmp);
    }
    catch (IllegalAccessException e)
    {
	throw e;
    }
    catch (NoSuchFieldException e)
    {
	throw e;
    }
    // The above mentioned change will not be reflected in the property. 
    // So, we need to update java.library.path ourselves.
    System.setProperty("java.library.path", path + File.pathSeparator 
          + System.getProperty("java.library.path"));
}

Thanks to the person who has actually written the code. I got it from some java forum and copy pasted it here. Typical software engineer. Right?? 😉

Advertisements