# java.lang.ClassCastException: class A cannot be cast to class B

**Code:** `ClassCastException` · **Category:** Java · **Seen on:** Java

An object was cast to a type it isn’t.

## 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

1. Use generics instead of raw types
2. Check with instanceof / pattern matching
3. Convert numbers via Number.longValue()

## Detailed fix by platform

### Java

1. `if (value instanceof Number n) { long id = n.longValue(); }`

## How to diagnose

1. **Types** — Both classes in the message
2. **Loaders** — Same class name in two loaders?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/java/classcastexception)
