Show Table of Contents
4.2.5. 调试和解决 ClassCastExceptions
ClassCastException 通常是类被不同于它扩展的类加载器加载而引起的,它也可能是因为在多个 JAR 里存在相同的类而引起的。
- 搜索应用程序来查找包含
ClassCastException里命名的类的所有 JAR。如果为这个类定义了模块,请从应用程序的 WAR 或 EAR 里查找并删除重复的 JAR。 - 找到包含这个类的 JBoss 模块并显性地在
MANIFEST.MF文件或jboss-deployment-structure.xml文件里定义依赖关系。关于更多的信息,请查看 https://access.redhat.com/site/documentation/JBoss_Enterprise_Application_Platform/ 上的《JBoss EAP 6 部署指南》里『类加载和模块』章节中的『类加载和子部署』。 - 如果您无法使用上面的步骤解决这个问题,您可以将类加载器的信息输出到日志里确定原因。例如,您可以在日志里看下列
ClassCastException:java.lang.ClassCastException: com.example1.CustomClass1 cannot be cast to com.example2.CustomClass2
- 在您的代码里,将
ClassCastException里出现的类的类加载信息输出到日志。例如:logger.info("Class loader for CustomClass1: " + com.example1.CustomClass1.getClass().getClassLoader().toString()); logger.info("Class loader for CustomClass2: " + com.example2.CustomClass2.getClass().getClassLoader().toString()); - 日志里的信息显示了哪些模块在加载类,且您需要根据您的应用程序删除或移走冲突的 JAR。

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.