Description
Casts involving generics are not checked at runtime because generic type information is not present in the bytecode. Hence such casts will provoke runtime exceptions only when the generic type is used. The snippet below demonstrates this problem. Such casts usually indicate a faulty design using of generics.
Type
Code Smell
Snippet
public class UncheckedGenericTypeOperation {
public static void main(String[] args) {
List<String> list = (List<String>) getAttributes(); // Noncompliant
String s = list.get(0); // exception
}
private static List<?> getAttributes() {
List<Integer> result = new ArrayList<>();
result.add(0);
return result;
}
}
Note
Also covered by Eclipse JDT.