Last active
September 7, 2017 20:20
-
-
Save mgrzeszczak/674e8b36c5c7da8c15c1bca4571aa5cb to your computer and use it in GitHub Desktop.
DynamicClassLoader for Java
This file contains 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
public final class DynamicClassLoader { | |
private final URLClassLoader classLoader; | |
private final Method addUrlMethod; | |
public DynamicClassLoader(URLClassLoader loader) { | |
classLoader = loader; | |
addUrlMethod = getAddUrlMethod(); | |
} | |
public DynamicClassLoader() { | |
classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); | |
addUrlMethod = getAddUrlMethod(); | |
} | |
private Method getAddUrlMethod() { | |
try { | |
Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); | |
addUrl.setAccessible(true); | |
return addUrl; | |
} catch (NoSuchMethodException e) { | |
throw new IllegalStateException(e); | |
} | |
} | |
public boolean register(URL url) { | |
try { | |
addUrlMethod.invoke(classLoader, url); | |
return true; | |
} catch (Exception e) { | |
return false; | |
} | |
} | |
public Optional<Class<?>> load(String name) { | |
try { | |
return Optional.of(classLoader.loadClass(name)); | |
} catch (ClassNotFoundException e) { | |
return Optional.empty(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment