java compilation_error ai_generated true

warning: [unchecked] unchecked cast to java.util.List<java.lang.String>

ID: java/compiler-warning-unchecked-cast

Also available as: JSON · Markdown · 中文
85%Fix Rate
82%Confidence
1Evidence
2023-02-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Java 8 active
Java 11 active
Java 17 active
Java 21 active

Root Cause

The compiler emits an unchecked cast warning when a generic type cast cannot be verified at runtime due to type erasure, indicating potential ClassCastException risk.

generic

中文

编译器在泛型类型转换由于类型擦除无法在运行时验证时发出未经检查的强制转换警告,表明存在 ClassCastException 风险。

Official Documentation

https://docs.oracle.com/javase/tutorial/java/generics/uncheckedCast.html

Workarounds

  1. 80% success Use a type-safe pattern with a helper method and @SuppressWarnings("unchecked") only on the minimal scope, with a comment explaining why it's safe: @SuppressWarnings("unchecked") List<String> list = (List<String>) someObject;
    Use a type-safe pattern with a helper method and @SuppressWarnings("unchecked") only on the minimal scope, with a comment explaining why it's safe: @SuppressWarnings("unchecked") List<String> list = (List<String>) someObject;
  2. 90% success Refactor the code to avoid unchecked casts by using generic methods or type tokens: public <T> T cast(Object obj, Class<T> clazz) { return clazz.cast(obj); }
    Refactor the code to avoid unchecked casts by using generic methods or type tokens: public <T> T cast(Object obj, Class<T> clazz) { return clazz.cast(obj); }

中文步骤

  1. Use a type-safe pattern with a helper method and @SuppressWarnings("unchecked") only on the minimal scope, with a comment explaining why it's safe: @SuppressWarnings("unchecked") List<String> list = (List<String>) someObject;
  2. Refactor the code to avoid unchecked casts by using generic methods or type tokens: public <T> T cast(Object obj, Class<T> clazz) { return clazz.cast(obj); }

Dead Ends

Common approaches that don't work:

  1. 30% fail

    Suppression only hides the symptom; the cast remains unchecked and dangerous.

  2. 50% fail

    Raw types bypass generic checks entirely, leading to potential heap pollution and runtime errors.