3

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')
7
  • Does this answer your question? Java Class cast Exception - Spring boot Commented May 30, 2023 at 14:39
  • 1
    You're doing something which is not valid anymore in Java 9 and higher. The type of the system classloader changed, so you can't just cast to URLClassLoader and expect it to work. Commented May 30, 2023 at 16:24
  • 2
    @MarkRotteveel to be more precise, this has never been valid at all. It just happened to work in a specific implementation. Commented May 31, 2023 at 9:49
  • 2
    Since this question has been tagged with “agent” and “instrumentation”, an explanation is needed why you don’t use the Instrumentation API but resort to this hack. Commented May 31, 2023 at 9:50
  • 2
    If you use an agent, then just call Instrumentation.appendToSystemClassLoaderSearch. Commented May 31, 2023 at 11:39

1 Answer 1

1

You you have tagged this question with both and - 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.