4.2.5. Debug and Resolve ClassCastExceptions

ClassCastExceptions often happen because a class is being loaded by a different class loader than the class it extends. They can also be a result of the same class existing in multiple JARs.
  1. Search the application to find all JAR(s) that contain the class named by the ClassCastException. If there is a module defined for the class, find and remove the duplicate JAR(s) from the application's WAR or EAR.
  2. Find the JBoss module containing the class and explicitly define the dependency in the MANIFEST.MF file or in the jboss-deployment-structure.xml file. For more information, refer to Class Loading and Subdeployments in the chapter entitled Class Loading and Modules in the Development Guide for JBoss EAP 6 on https://access.redhat.com/site/documentation/JBoss_Enterprise_Application_Platform/.
  3. If you are not able to resolve it using the steps above, you can often determine the cause of the problem by printing the class loader information to the log. For example, you see the following ClassCastException in the log:
    java.lang.ClassCastException: com.example1.CustomClass1 cannot be cast to com.example2.CustomClass2
    1. In your code, print the class loader information for the classes named by the ClassCastException to the log, for example:
      logger.info("Class loader for CustomClass1: " + 
            com.example1.CustomClass1.getClass().getClassLoader().toString());
      logger.info("Class loader for CustomClass2: " + 
            com.example2.CustomClass2.getClass().getClassLoader().toString());
      
    2. The information in the log shows which modules are loading the classes and, based on your application, you need to remove or move the conflicting JAR(s).