Search code examples
javaclassloader

Debug ClassCastException


I run into a ClassCastException:

Cannot cast my.package.classA to my.package.classA.

Note that the (canonical) class (name) is the same.

I understand this should be related to different class loaders and/or loading the class from different jars. The project is built using Maven. Can I debug somehow which classloader was used in each case and from which jar the classes have been loaded?


Solution

  • Add a breakpoint for ClassCastException. For IntelliJ, this looks something like this:

    IntelliJ breakpoint

    Once the exception is caught, navigate in the debugger call hierarchy until you find the line where the cast should happen and you have a reference to both classes.

    For example:

    enter image description here

    Now, you can inspect both classes (in my case typeClass and instanceClass). The class holds a reference to it's class loader.

    In my case, it's ModuleClassLoader for Module "my.ear" from Service Module Loader and ModuleClassLoader for Module "my-web-app.war" from Service Module Loader

    enter image description here

    As you can see, one class is coming from the ear, the other one from the war.

    Change the dependency to provided in the web-app pom.xml, that should solve the problem.

    Note that the war file will not run anymore outside of the ear, if you need both scenarios, use a Maven profile.