There are cases where we need to add classpath at runtime. For example adding jar to classpath, but depends on configuration or some logic at runtime.

The class who responsible for handling classpath list is URLClassloader.
You can get current system URLClassLoader with:
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

If you check javadoc about this class you’ll see:

protected void addURL(URL url)
Appends the specified URL to the list of URLs to search for classes and resources.

So you’ll just need to call the addUrl method to add new path/jar file.
But wait a minute, the method is protected… :( do I need to create a subclass or put the caller class on same package?
Creating a subclass is one way to do it, but there’s simpler way (I’ll create article about creating URLClassLoader subclass next time :p)

Here come the savior : Reflection
By using reflection we can break OOP concept about encapsulating method. It’s feel good to break the rules right (warning : use this at your own risk, you know you’re breaking the OO rule. So I won’t responsible if your computer explode or you’ll fighting with OO fans because of this)

Here a sample how to called it with reflection:

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.invoke(urlClassLoader, new Object[]{u});

Happy reflecting.. :)

About these ads