I'm running some code inside JUnit inside IntelliJ and I'm getting an exception
java.lang.LinkageError: ClassCastException: attempting to castjar:file:/C:/zzz/zzz/web/WEB-INF/lib/jakarta.ws.rs-api-2.1.6.jar!/javax/ws/rs/ext/RuntimeDelegate.class to jar:file:/C:/zzz/zzz/web/WEB-INF/lib/jakarta.ws.rs-api-2.1.6.jar!/javax/ws/rs/ext/RuntimeDelegate.class
An the top of the stack trace is:
at javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:124)
at javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:96)
at javax.ws.rs.core.MediaType.toString(MediaType.java:395)
at com.itf.remote.client.AutoTestingRestClient.doGet(AutoTestingRestClient.java:141)
the code line where it happens:
HttpResponse response = client.doGet(uri, MediaType.APPLICATION_JSON_TYPE.toString());
and it's the toString() method that causes it.
the jar file above is on the classpath only once. What IntelliJ runs is:
C:\Users\loosp\.jdks\temurin-17.0.8\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576
"-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2\lib\idea_rt.jar=34089:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.2\bin" -Dfile.encoding=UTF-8 -classpath "
... I removed all jars from here " com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 randstad.junit.ITFTest,Test1
From my investigation so far I understand that the class RuntimeDelegate must have been loaded by 2 different class loaders. But how is that possible? This is happening inside jakarta.ws.rs-api-2.1.6.jar so I'm pretty sure I can trust that.
Any ideas welcome.
I already decompiled the code that this is happening in and it's this method:
private static RuntimeDelegate findDelegate() {
try {
Object delegate = FactoryFinder.find("javax.ws.rs.ext.RuntimeDelegate", "org.glassfish.jersey.internal.RuntimeDelegateImpl", RuntimeDelegate.class);
if (!(delegate instanceof RuntimeDelegate)) {
Class pClass = RuntimeDelegate.class;
String classnameAsResource = pClass.getName().replace('.', '/') + ".class";
ClassLoader loader = pClass.getClassLoader();
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
URL targetTypeURL = loader.getResource(classnameAsResource);
throw new LinkageError("ClassCastException: attempting to cast" + delegate.getClass().getClassLoader().getResource(classnameAsResource) + " to " + targetTypeURL);
} else {
return (RuntimeDelegate)delegate;
}
} catch (Exception var5) {
throw new RuntimeException(var5);
}
}
But still no idea how can this happen?