Search code examples
javaclassloaderclasscastexception

classcast exception from a extension class loaded class


Ran into a issue today.

abc.ClassA a = (abc.ClassA) request.getsession().getAttribute();

and i get classcast exception here.

abc.ClassA is referenced from a jar file in the project build path.

I also read about the class being loaded with different class loaders and the issue could be becoz of that.


Solution

  • Your class was loaded by two different classloaders.
    I guess your jar is located twice in the classloaders hierarchy: once somewhere in the parent path (lib of weblogic?) and once at a child (war?)

    The best solution is putting a jar only once at classpath.

    If this is impossible, you can try to change client-first/client-last behavior of classloaders.

    Tip: you can debug it and get the problematic classloaders quite easily. Stop in debugger in the problematic line and then compare request.getsession().getAttribute().getClass().getClassloader() and abc.ClassA.class.getClassloader()