Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

classpath

In order to better understand how things works in Java, I'd like to know if I can dynamically add, at runtime, a directory to the class path.

For example, if I launch a .jar using "java -jar mycp.jar" and output the java.class.path property, I may get:

java.class.path: '.:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java' 

Now can I modify this class path at runtime to add another directory? (for example before making the first call to a class using a .jar located in that directory I want to add).

like image 386
Cedric Martin Avatar asked Oct 25 '11 03:10

Cedric Martin


People also ask

How do I include all JARs in a folder classpath?

In general, to include all of the JARs in a given directory, you can use the wildcard * (not *. jar ). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name.


2 Answers

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

like image 178
Jonathan Spooner Avatar answered Oct 29 '22 00:10

Jonathan Spooner


Update 2014: this is the code from the accepted answer, by Jonathan Spooner from 2011, slightly rewritten to have Eclipse's validators no longer create warnings (deprecation, rawtypes)

//need to do add path to Classpath with reflection since the URLClassLoader.addURL(URL url) method is protected: public static void addPath(String s) throws Exception {     File f = new File(s);     URI u = f.toURI();     URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();     Class<URLClassLoader> urlClass = URLClassLoader.class;     Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});     method.setAccessible(true);     method.invoke(urlClassLoader, new Object[]{u.toURL()}); } 
like image 32
knb Avatar answered Oct 29 '22 02:10

knb