Getting class cast exception where both classes are exactly the same

不想你离开。 提交于 2019-11-26 19:01:14

This happens when two different ClassLoader objects load classes with the same name. The equality of two classes in Java depends on the fully qualified name and the class loader that loaded it.

So if two independent class loaders load classes from the same location, then objects of those types will not be able to be cast to each others type, even if their classes are called the same.

As Joachim explained earlier, java.lang.ClassCastException typically occurs when two classloaders load the classes with the same name. However, i have come across another situation when this could occur.

This could occur with some IDE's that automatically reloads classes that have been modified. In such cases there might be older versions of the class retained in memory causing ClassCastException.

Here are a few ways you could resolve this issue :

  1. If you are writing a custom class loader, while loading a class make sure that the base/default class loader does not already have an instance of that class loaded.

  2. Make the class being loaded a sub-class of the class that is already loaded by the default class loader.

  3. Make the class being loaded implement an interface that is already loaded by the default class loader.

More info here - http://www.jspwiki.org/wiki/A2AClassCastException

This is because the class has been loaded by two different classloaders. You cannot cast between them.

You've likely got a duplicate copy of CsiTipoLav in your application, and the two different copies are being loaded at different times from different classloaders. JBoss has a plethora of different classloaders in a hierarchy, and it's easy to get things in a twist.

Make sure you only have one copy of the class.

The object you are trying to cast, is loaded by a different classloader than the one which has loaded the class you are trying to cast into.

In my case i had two different *.ear and wanted to load a class from the other. So i had to isolate the classloader. I used this description:

http://www.thorgull.be/wiki/index.php?title=ClassLoader_isolation_in_JBOSS

It worked for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!