Sunday, April 06, 2008

How To Modify Classpath At Runtime?

I am designing a quite large system that one of the user interfaces is based on Java Swing GUI library. Each subsystem is a standalone application itself that can be used separately if appropriate conditions issued, however they also are plugins within the central UI infrastructure.

If application is standalone, authentication is its own and other applications are not visible. If application is connected as a plugin within the infrastructure, then common authentication mechanism is used and tight integration with other applications appears.

Whatever, during some investigations, I needed to modify my $CLASSPATH at JVM runtime. For curious people how it is done, here is a source below. Enjoy:


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;


public class ClassPathModificator {
private static final Class[] urlParams =
new Class[]{URL.class};
public static void appendPath(URL newURL) throws
IOException {
URLClassLoader classLoader = (URLClassLoader)
ClassLoader.getSystemClassLoader();
try {
Method meth = URLClassLoader.class.
getDeclaredMethod("addURL", urlParams);
meth.setAccessible(true);
meth.invoke(classLoader, new Object []
{newURL});
} catch (Throwable err) {
throw new IOException();
}
}

public static void appendPath(String newPath)
throws IOException {
appendPath(new File(newPath));
}

public static void appendPath(File fileObj)
throws IOException {
appendPath(fileObj.toURL());
}
}



P.S. Extremely stupid Blogger's interface does not allows me to make it nicer, so I had to give up colorize the code and had to wrap it that ugly... :-(

No comments: