java.lang.ClassCastException: class A cannot be cast to class B
An object was cast to a type it isn’t.
cannot be cast to class Meaning
Raw collections, deserialized data (Integer vs Long), and objects from different class loaders (same class name, different loader) commonly cause it.
Common causes
- Wrong assumption about runtime type
- Raw/untyped collections
- JSON numbers deserialized as Integer vs Long
- Class loader duplicates in app servers
⚡ Quick fix
- Use generics instead of raw types
- Check with instanceof / pattern matching
- Convert numbers via Number.longValue()
Detailed fix by platform
Java
if (value instanceof Number n) { long id = n.longValue(); }
How to diagnose
- Types — Both classes in the message
- Loaders — Same class name in two loaders?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in Java
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 12 Oct 2026