BackendBench
Coffee

Home โ€บ Java exceptions โ€บ ClassCastException

Unchecked exception ยท java.lang

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.String

Extends 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

How to fix it

  1. Check with instanceof first, and prefer pattern matching: if (o instanceof String s).
  2. Avoid raw types and fix unchecked warnings; use typed generics and a TypeReference with Jackson.
  3. If the message mentions two loaders, look for duplicate jars on the classpath or in the shared library folder.
  4. Redesign with polymorphism so you do not need the cast at all.

Broken and fixed

fails
Object value = cache.get("count");
String text = (String) value; // value is an Integer
works
if (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.

Related exceptions

More tools you might need