英文:
Debug ClassCastException
问题
我遇到了一个 ClassCastException
:
无法将my.package.classA强制转换为my.package.classA。
请注意,(规范的)类(名)是相同的。
我理解这应该与不同的类加载器和/或从不同的JAR包加载类有关。
该项目使用Maven构建。
我能以某种方式调试出每种情况下使用了哪个类加载器,以及从哪个JAR包加载了这些类吗?
英文:
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?
答案1
得分: 4
为ClassCastException
添加一个断点。
对于IntelliJ,看起来是这样的:
一旦捕获到异常,在调试器的调用层次结构中导航,直到找到应该发生转换的那一行,并且你拥有对两个类的引用。
例如:
现在,你可以检查这两个类(在我的情况下是typeClass
和instanceClass
)。该类保存对其类加载器的引用。
在我的情况下,它是ModuleClassLoader for Module "my.ear" from Service Module Loader
和
ModuleClassLoader for Module "my-web-app.war" from Service Module Loader
如你所见,一个类来自于ear,另一个来自于war。
在web-app的pom.xml
中将依赖项更改为provided
,这应该可以解决问题。
请注意,war文件将不再在ear之外运行,如果你需要两种情景,可以使用Maven配置文件。
英文:
Add a breakpoint for ClassCastException
.
For IntelliJ, this looks something like this:
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:
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
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论