2

I have a library I used to use in my java program.

It contains next line:

URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();

It works ok on java8, but after I tried to launch it on java11 I got the ClassCastException

java.lang.ClassCastException: class jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to class java.net.URLClassLoader

Is it possible to solve this pb without modifying library? AFAIK, Java should be backward compatible, so maybe some command-line argument might help?

Thank you

Limmy
  • 697
  • 1
  • 13
  • 24
  • 6
    this change was introduce in java-9 and there was never an official specification that said application class loader must be an instance of `URLClassLoader`, so there is nothing backwards compatibility here. If you want help, you might as well explain what you were doing with the resulting class-loader. – Eugene Feb 10 '19 at 16:56
  • Java 9 brought some changes that invalidated some assumptions. This is one of those assumptions. Maybe there's a workaround, but it's likely that the library needs an update. Related post: https://stackoverflow.com/questions/46694600/java-9-compatability-issue-with-classloader-getsystemclassloader – ernest_k Feb 10 '19 at 16:59
  • Unfortunatelly, not my code use `URLClassLoader` and I can't modify it directly :( – Limmy Feb 10 '19 at 17:09
  • Well... I hope you have properly islolated the foreing library from your core application through some interface and can now switch to a different implementation or implement your own :) – Turing85 Feb 10 '19 at 17:11

1 Answers1

3

Java is backwards-compatible. Looking at ClassLoader.getSystemClassLoader() in Java 8 shows that it returs a ClassLoader-instance, not a URLClassLoader-instance. The same is true for ClassLoader.getSystemClassLoader() in Java 11. Thus, there were never any guarantees that ClassLoader.getSystemClassLoader() returns an URLClassLoader.


As far as I know, there is no way to transform a ClassLoader to an URLClassLoader. The only proper way to fix this issue is to write the maintainers of the library and telling them that they relied on some implementation detail, that they shouldn't have done so and ask them to fix the issue. If it is an easy fix and the project is open-source, you can fork the project, fix the issue and create a pull request.

Turing85
  • 18,217
  • 7
  • 33
  • 58