Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Modify Classpath At Runtime

843798Sep 17 2002 — edited Jan 20 2010
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:
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 17 2010
Added on Sep 17 2002
59 comments
5,651 views