javagenericsjlsunchecked-cast

Why Variable-Parameterized variant of (cast) operator in Java is flagged as unchecked warning and not error?


Consider the following snippet:

class MyClass<E>{
...
public void checkType(Object o){
 if(o instanceof List<E>){ //this gives compilation error
   List<E> list = (List<E>)o; //this gives unchecked warning
 }
}
...
}

I'm not sure if there can be any case why this will not be an error and only qualify as warning.


Solution

  • Just came across this piece of code that suggests why Non-Reified Casts with Type Parameters can be a warning only and not an error:

    public static <T> List<T> getAsList(Collection<T> c){
            if(c instanceof List<?>){
                return (List<T>)c;
            }
            ...
        }