Created
September 14, 2016 21:14
-
-
Save dmarcuse/28b4fe1f27f2aae9e2c4bd0e4ccac56c to your computer and use it in GitHub Desktop.
Add jars to the classpath at runtime!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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