I created a custom class to add urls into a class loader dynamically.
void addURL(URL url) {
try {
Class<?>[] parameters = new Class[]{URL.class};
Class<?> sysclass = URLClassLoader.class;
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
URLClassLoader sysloader = (URLClassLoader) (getClass().getClassLoader());
while (sysloader != null) {
method.invoke(sysloader, url);
sysloader = (URLClassLoader) sysloader.getParent();
}
}catch (Exception e) {
e.printStackTrace();
}
}
And then I'm trying to add the url with the following method
String filePath = "jar path";
File file = new File(filePath);
URL url = file.toURI().toURL();
CustomClassLoader customURLClassLoader = new CustomClassLoader();
customURLClassLoader.addURL(url);
I'm getting the following exception
java.lang.ClassCastException: 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')