Home โบ Java exceptions โบ ClassCastException
ClassCastException: causes and fixes
An object was cast to a type it is not an instance of.
What it looks like
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.StringExtends RuntimeException in java.lang.
What it means
A cast such as (String) obj is checked at run time. If the object is not an instance of the target class or one of its subclasses, the JVM throws ClassCastException. The message names both classes, and for classes in different modules or class loaders it also tells you which loader defined each, which is the key to class-loader problems in application servers.
Common causes
- Raw types and unchecked generics: a
List<String>that actually holds integers because of heap pollution. - Deserialising JSON into
Objectand casting, when Jackson produced a LinkedHashMap instead of your class. - The same class loaded by two class loaders (a duplicate jar, or hot reload), so the "same" class is not assignable to itself.
- Casting down a hierarchy without checking the type first.
How to fix it
- Check with
instanceoffirst, and prefer pattern matching:if (o instanceof String s). - Avoid raw types and fix unchecked warnings; use typed generics and a
TypeReferencewith Jackson. - If the message mentions two loaders, look for duplicate jars on the classpath or in the shared library folder.
- Redesign with polymorphism so you do not need the cast at all.
Broken and fixed
Object value = cache.get("count");
String text = (String) value; // value is an Integerif (cache.get("count") instanceof Integer n) {
String text = String.valueOf(n);
}๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
A "cannot be cast to class X (X is in unnamed module of loader ...)" message with two different loaders points to a packaging problem, typical with Spring Boot devtools restarts and with shared libraries in Tomcat.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is ClassCastException a checked or unchecked exception?
ClassCastException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is ClassCastException in?
It lives in java.lang, so the import is import java.lang.ClassCastException; (java.lang needs no import).
What is the first thing to check when I see ClassCastException?
Read the message and the first stack trace line in your own code. The usual causes are: Raw types and unchecked generics: a List<String> that actually holds integers because of heap pollution; and Deserialising JSON into Object and casting, when Jackson produced a LinkedHashMap instead of your class.