Skip to content

Instantly share code, notes, and snippets.

@yeshuibo
Forked from dmarcuse/ClasspathHacker.java
Created April 2, 2020 10:51
Show Gist options
  • Save yeshuibo/e77fbaf45e99645a11ac5ceef9455182 to your computer and use it in GitHub Desktop.
Save yeshuibo/e77fbaf45e99645a11ac5ceef9455182 to your computer and use it in GitHub Desktop.
Add jars to the classpath at runtime!
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
*
* @author apemanzilla
*
*/
public final class ClasspathHacker {
/**
* Hacks the system classloader to add a classpath entry at runtime.<br /><br />
*
* <b>Example</b><br /><br />
* {@code ClasspathHacker.addToClasspath(new File('example.jar'));}<br />
* {@code ClassInExampleJar.doStuff();}
*
* @param file The jar file to add to the classpath
*/
public static void addToClasspath(File file) {
try {
URL url = file.toURI().toURL();
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
} catch (Exception e) {
throw new RuntimeException("Unexpected exception", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment