Can a directory be added to the class path at runtime?

You can use the following method:

URLClassLoader.addURL(URL url)

But you’ll need to do this with reflection since the method is protected:

public static void addPath(String s) throws Exception {
    File f = new File(s);
    URL u = f.toURL();
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class urlClass = URLClassLoader.class;
    Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(urlClassLoader, new Object[]{u});
}

See the Java Trail on Reflection. Especially the section Drawbacks of Reflection

Leave a Comment