Different classloaders cause ClassCastException when persisting data via Spring

classloader, java, jdo, spring, spring-mvc

Solution

There doesn't need to be two different versions of the class for a class cast exception to appear. Even the same class definition is seen as two different classes when loaded by two distinct classloaders. Which seems to be the case here.

Unfortunately I am not familiar with the platforms you use, so I can't give more concrete advice than this: try to experiment with moving the jar containing your `Test` class to different places on your web app classpath, and/or reconfiguring the Spring and Jetty classloaders so that both delegate the loading of `Test` to the same parent classloader.

Problem

I'm creating an MVC Spring webapp. Using: Jetty (servlet container), DataNucleus (dao platform), DB4O (embedded datastore). When I persist an object (done from within a Spring Controller) using JDO from DataNucleus, it stores to the DB fine. ``` @PersistenceCapable public class Test { @Persistent private String testString; //getter-setters implemented } ``` When I do a simple query for the objects I previously added I get a `ClassCastException` on my Test class (can't cast `a.b.c.Test` to `a.b.c.Test`). The classloader of Test returned by JDO is (toString) `[sun.misc.Launcher$AppClassLoader@5acac268]`, the classloader of the Test class before I persisted it to the DB is `[WebAppClassLoader@1593275665]` I've gotten this far, but I don't really know what to do with a classloader issue like this, I've never spent much thought on classloaders before. Any direction is helpful.

Original source