Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active March 16, 2025 16:59
Show Gist options
  • Select an option

  • Save simonwoo/0338424508496b6e171e to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/0338424508496b6e171e to your computer and use it in GitHub Desktop.
add new class path at runtime in java

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.setAccessible(true);
  method.invoke(urlClassLoader, new Object[]{u});
}
@yjr930
Copy link

yjr930 commented Apr 18, 2023

useful for me! thx!

@mzattera
Copy link

mzattera commented Oct 3, 2023

I am getting this when casting to URLClassLoader

class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader (jdk.internal.loader.ClassLoaders$AppClassLoader and java.net.URLClassLoader are in module java.base of loader 'bootstrap')

@Beengoo
Copy link

Beengoo commented Mar 16, 2025

I am getting this when casting to URLClassLoader

In java 9+ its now impossible to load classes like that.
You need to use java 8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment