ClassCastException when casting to the same class

前端 未结 11 931
小蘑菇
小蘑菇 2020-11-22 07:09

I have 2 different Java projects, one has 2 classes: dynamicbeans.DynamicBean2 and dynamic.Validator.

On the other project, I load both of

11条回答
  •  长情又很酷
    2020-11-22 07:55

    I am not quite following your description of the program flow, but usually when you get ClassCastExceptions you cannot explain you have loaded the class with one classloader then try to cast it to the same class loaded by another classloader. This will not work - they are represented by two different Class objects inside the JVM and the cast will fail.

    There is an article about classloading in WebSphere. I cannot say how it applies to your application, but there are a number of possible solutions. I can think of at least:

    1. Change the context class loader manually. Requires that you can actually get a reference to an appropriate class loader, which may not be possible in your case.

      Thread.currentThread().setContextClassLoader(...);
      
    2. Make sure the class is loaded by a class loader higher in the hierarchy.

    3. Serialize and deserialize the object. (Yuck!)

    There is probably a more appropriate way for your particular situation though.

提交回复
热议问题