Video in progress

Strong Middle ☕ Core Java

How does the error "com.shop.User cannot be cast to com.shop.User" come about?

The same class was loaded by two different ClassLoaders. For the JVM, a class is its name plus the loader that loaded it, so these are two different types, and one can't be cast to the other.

📖 Answer

In the JVM, User.class isn't unique: (com.shop.User, loaderA) and (com.shop.User, loaderB) are two different types. If an object was created from a class in one loader and is cast to the class in another, you get this error.

Common cases:

  • Spring Boot DevTools. It loads the application classes in a separate "restart" ClassLoader. If a cache (for example, Redis or Ehcache) or a library deserializes an object through the base loader, you get exactly this error. The sign: it appears only in the local environment, after a hot reload.
  • Application servers / plugin systems. The same jar sits both in WEB-INF/lib and in the server's shared lib.
  • A duplicate inside a fat jar. Two versions of the same library ended up in different modules.

It's easy to check:

log.info("obj loader: {}", obj.getClass().getClassLoader());
log.info("target loader: {}", User.class.getClassLoader());

The JVM flag -verbose:class (or -Xlog:class+load) shows where each class was loaded from.

Related errors: LinkageError: loader constraint violation, and NoSuchMethodError, which often means two versions of one library are on the classpath (look for them with mvn dependency:tree).

The fix is to keep the class in a single loader: remove the duplicate jar, configure restart.include/exclude in DevTools, or pass objects across the loader boundary in a neutral format like JSON.