4

To load dynamically a jar to classpath I used to use the following code with Java 8.

File file = new File(jarPath);
URL u =  f.toURI().toURL();     
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[]{u});

However using Java 11 does not work anymore. I have tried some solution provided in the internet but none of them works for me.
Please could you help me to resolve this problem.
Thanks

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
mariem
  • 41
  • 1
  • 2
  • 1
    I'm guessing (since you didn't say one way or the other) that the cast to `URLClassLoader` is failing? Even if I'm correct you should post a [mre] demonstrating the problem and the error(s) you're getting. Also note that simply saying "I have tried some solution [...] but none of them works for me" doesn't say much. _What_ are the solutions you tried? _How_ did they not work? If you don't specify then you risk getting the same exact solutions again. See [ask]. – Slaw Nov 22 '19 at 15:27
  • 1
    You have to create a *new* `URLClassLoader` instead of trying to hack the system class loader. – Holger Nov 22 '19 at 16:09
  • 1
    Loading classes dynamically in Java 11 has no difference to Java 8: [How should I load Jars dynamically at runtime?](https://stackoverflow.com/questions/60764/how-should-i-load-jars-dynamically-at-runtime) – ZhekaKozlov Nov 23 '19 at 06:48
  • Please check: https://stackoverflow.com/questions/68380968/java-11-issue-with-adding-dependency-jars-at-runtime – Valsaraj Viswanathan Sep 17 '21 at 12:34

0 Answers0