Sunday, August 12, 2007

Modify Classpath At Runtime

I've seen a lot of forum posts about how to modify the classpath at runtime and a lot of answers saying it can't be done. I needed to add JDBC driver JARs at runtime so I figured out the following method.

The system classloader (ClassLoader.getSystemClassLoader()) is a subclass of URLClassLoader. It can therefore be casted into a URLClassLoader and used as one.

URLClassLoader has a protected method addURL(URL url), which you can use to add files, jars, web addresses - any valid URL in fact.

Since the method is protected you need to use reflection to invoke it.

Here's some code for a class which adds a File or URL to the classpath:

import java.lang.reflect.*;
import java.io.*;
import java.net.*;
public class ClassPathHacker {

private static final Class[] parameters = new Class[]{URL.class};

public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method

public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method


public static void addURL(URL u) throws IOException {

URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;

try {
Method method = sysclass.getDeclaredMethod("addURL",parameters);
method.setAccessible(true);
method.invoke(sysloader,new Object[]{ u });
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch

}//end method

}//end class

No comments: