Java casting / classloader issues

前端 未结 4 513
轻奢々
轻奢々 2021-01-14 17:10

Here is the simplified version of the problem:

 SomeClass c = (SomeClass) obj.getSomeClassParent()

not always but it happens sometimes to t

4条回答
  •  误落风尘
    2021-01-14 17:49

    I think it can happen if

    1. a SomeClass instance was loaded from ClassLoader X (so its class is SomeClass of CL X or let's call it: CL(X).SomeClass)
    2. but it is being cast in a different class loader. E.g. the current Threads class loader is Y so SomeClass is actually CL(Y).SomeClass

    So you have:

    • instance class = CL(X).SomeClass
    • class cast target = CL(Y).SomeClass

    Or in other words - not the same class - thus the class cast exception.


    Possible duplicate of: ClassCastException when casting to the same class - it has some good suggestions as well.

提交回复
热议问题