These days i'm finalising the FIRE regular expression compiler. To add a feature, the need arise to modify the classpath at runtime. It was a surprise for me when i discovered that there is no official way to modify this at runtime. I even created my own URLClassLoader (java.net), and set it as default classloader for my thread, but nothing.

I searched in google a little and found this post on a forum, which provided a class named ClassPathHacker that could add a path or file (jar) to a classpath at runtime. All this by a programmer named Antony Miguel. Well done :).

The source code of the class follows:
import java.net.*;
import java.io.*;
import java.lang.reflect.*;

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);
	}
	 
	public static void addFile(File f) throws IOException {
		addURL(f.toURL());
	}	 
	 
	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");
		}		
	}	
}
and an example of usage ..
import java.io.*;

public class ClassPathAdder {
	public static void main(String[] args) {
		try {
			ClassPathHacker.add(new File("/home/user/newClassPath"));
		} catch (IOException e) {
			System.err.println("Error - " + e.toString());
		}
	}
}
Cool! :-D