I'm debugging application about ClassCastException and end up with the following problem: I have class ServletContextImpl which extend ServletContext and a method getServletContext of ServletContext class return ServletContext type.
When I try the cast (ServletContextImpl)getServletContext() I get ClassCast Exception even the output of the call getServletContext().getClass().getName() return actually ServletContextImpl.
I don't understand the operator cast or instanceof check what to decide the object IS A X or not.
Any help to debug my problem would be very appreciated. PS. I know the application customize the ClassLoader. Is there any relationship whith the cast?
[Ben]: PS. I know the application customize the ClassLoader. Is there any relationship whith the cast?
Yes. Assuming that getClass().getName() returns the same package name as well as class name, this is probably the problem. If the exact same class is loaded by two different class loaders (and not by some shared ancestor class loader which defines the requested class), then it's really two different classes as far as Java is concerned. Application servers will do this sort of thing to prevent different applications from affecting each other - static variables in one class, loaded by one application, won't affect the same variables in the same class loaded by a different application. you can call getClass().getClassLoader() to identify which classloader loaded a class, and compare to ServletContextImpl.class.getClassLoader().
Ultimately the best solution here is generally to not cast to ServletContextImpl, but instead just use ServletContext. If you really, really need to call other methods, you might be able to get at them using reflection - but I would avoid this if possible.