java runtime_error ai_generated true

java.lang.ClassCastException

ID: java/classcastexception

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
65Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

ClassCastException is thrown when code attempts to cast an object to a type that is not an instance of that type. Common with raw types, generic type erasure, and incorrect assumptions about runtime types.

generic

Workarounds

  1. 92% success Use proper generics to enforce type safety at compile time, eliminating the need for runtime casts
    1. Replace raw types (List, Map) with parameterized types (List<String>, Map<String, Integer>). 2. Avoid raw type assignments that bypass generic type checking. 3. Use bounded wildcards (? extends T, ? super T) for flexible but type-safe APIs. 4. When deserializing from external sources, use TypeReference<T> or equivalent to preserve generic type information.
  2. 88% success Use instanceof with pattern matching (JDK 17+) to safely check and cast types
    1. Replace unsafe casts with pattern matching: 'if (obj instanceof String s) { use(s); }'. 2. For sealed class hierarchies, use switch with pattern matching (JDK 21+) for exhaustive type handling. 3. When the type mismatch is due to classloader issues (same class loaded by different classloaders), ensure a single classloader is used or compare by class name instead of identity.

Dead Ends

Common approaches that don't work:

  1. Suppressing the unchecked cast warning with @SuppressWarnings("unchecked") without verifying runtime types 80% fail

    The @SuppressWarnings annotation only hides the compiler warning; it does not make the cast safe. The ClassCastException will still occur at runtime. Suppressing warnings without verification masks the exact problem that needs to be fixed.

  2. Adding multiple cascading instanceof checks to handle every possible type 50% fail

    Cascading instanceof checks are brittle and violate the open-closed principle. When new types are added, the checks must be updated everywhere. This approach indicates a design problem — typically a missing interface, improper use of generics, or a need for the visitor pattern.

Error Chain

Leads to:
Preceded by:
Frequently confused with: