samedi 7 mars 2015

Why is this an unchecked cast? And how to fix it?



I have the following code:



public final <T extends Component> T getComponent(Class<T> type) {
Iterator<Component> it = components.iterator();

while(it.hasNext()) {
Component next = it.next();

if(type.isAssignableFrom(next.getClass()))
return (T)next; // Why is this an unchecked cast from Component to T?
}

return null;
}


And for some reason, return (T)next; is an unchecked cast from Component to T.


I'm not sure as to why this is, because T has to extend Component, it should be able to safely cast it to any subclasses of Component, right?


If I manually do return (TestComponent)next; and change the return type to TestComponent it works fine, so why doesn't it work with T?




Aucun commentaire:

Enregistrer un commentaire