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.lang.reflect.Method;

public class ClassPathModificator {
private static final Class[] urlParams =
new Class[]{URL.class};
public static void appendPath(URL newURL) throws
IOException {
URLClassLoader classLoader = (URLClassLoader)
try {
Method meth = URLClassLoader.class.
getDeclaredMethod("addURL", urlParams);
meth.invoke(classLoader, new Object []
} 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 {

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: