Compile error using swing code

So it’s not a Scala problem. This line in Java:

final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

is roughly equivalent to this in Scala:

val sysloader: URLClassLoader = ClassLoader.getSystemClassLoader().asInstanceOf[URLClassLoader]

The return type of ClassLoader.getSystemClassLoader() is ClassLoader, so there is no guarantee that the returned value is of type URLClassLoader. It just happened to be in Java 8, but is no longer in Java 11.

2 Likes

I believe this is because of a change that happened between Java 8 and Java 9 when modules were introduced. Unfortunately, I have a large Java project that allows dynamic loading of classes which breaks on any version of Java above Java 8 for this exact reason. The fact that the system class loader happened to be a URLClassLoader from Java 2 until Java 8 still doesn’t make it a safe cast.

In the Java 11 API, it looks like the basic ClassLoader type has a findClass method, so this cast shouldn’t be needed. I say that, though I haven’t tried it. That method has been there since 1.2 so for this usage, it might be happy and general across any version of Java that isn’t ancient.

2 Likes