Introduction
This article is a non-recommended hack for dynamically adding a class path to SystemClassLoader
. You should re-think your design before using this hack; usually, you should be able to use URLClassLoader
to load whatever you want.
About SystemClassLoader
SystemClassLoader
s are usually URLClassLoader
s, and in URLClassLoader
, there is a method called addURL()
, so we can make use of this to add paths/jars to SystemClassLoader
dynamically at runtime. However, since "addURL()
" is a protected method, we have to use Reflection to call it.
The sample code is as follows:
public static void addURLs(URL[] urls) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
if ( cl instanceof URLClassLoader ) {
URLClassLoader ul = (URLClassLoader)cl;
Class<?>[] paraTypes = new Class[1];
paraTypes[0] = URL.class;
Method method = URLClassLoader.class.getDeclaredMethod("addURL", paraTypes);
method.setAccessible(true);
Object[] args = new Object[1];
for(int i=0; i<urls.length; i++) {
args[0] = urls[i];
method.invoke(ul, args);
}
} else {
}
}
Test
I have written a test case, and it will automatically load all "lib/*.jar" and instantiate an object as specified in args[0]
. The test output is as follows. Note: I only included "bin" as my class path, and I have commons-collections.jar under my "lib" directory, but the program is still able to dynamically load the required class.
History