Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jdk.internal.loader.ClassLoaders$AppClassLoader incompatible with java.net.URLClassLoader (j8 - j11)

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')
like image 560
hotcoder Avatar asked Jan 17 '26 18:01

hotcoder


1 Answers

You you have tagged this question with both agent and instrumentation - so you may actually be interested in adding a jar to the system class loader from a javaagent.

The Instrumentation interface already has a supported method to do exactly that: Instumentation.appendToSystemClassLoaderSearch.

By using this supported method you avoid all the problems that the reflective solution has - as this method is part of Java, it will be updated to account for any internal changes - preserving its functionality.

like image 116
Johannes Kuhn Avatar answered Jan 19 '26 19:01

Johannes Kuhn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!