Skip to content

Instantly share code, notes, and snippets.

@dmarcuse
Created September 14, 2016 21:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dmarcuse/28b4fe1f27f2aae9e2c4bd0e4ccac56c to your computer and use it in GitHub Desktop.
Save dmarcuse/28b4fe1f27f2aae9e2c4bd0e4ccac56c 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