Video in progress
How does a "com.app.User cannot be cast to com.app.User" error come about?
In the JVM a class's identity is the pair of its name and the classloader that loaded it. If the same class is loaded by two different loaders, the JVM sees them as two different types and the cast fails.
📖 Answer
The message looks strange because the names are identical. But to the JVM, User@AppLoader and User@RestartLoader are completely different classes.
The most common place in practice is Spring Boot DevTools. It loads your application code through a RestartClassLoader and the libraries through the ordinary loader. Say a cache library (for example a Redis serializer or EhCache) deserializes an object and finds the class from its own loader. You then cast the result to the User in your own code, and this error appears.
Other examples:
- on an application server, two webapps exchange an object through one shared cache;
- a plugin system where every plugin has its own
URLClassLoader; - OSGi.
It is easy to check:
System.out.println(obj.getClass().getClassLoader());
System.out.println(User.class.getClassLoader());
If you get two different loaders, you have found the cause. The fix depends on the situation: in DevTools, add the problem jar to the restart loader through META-INF/spring-devtools.properties; on a server, move the shared class to a shared (parent) loader, or pass the object across the boundary as JSON or bytes.
Sign up to mark studied questions and save your progress.