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?
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
The warning message “unchecked conversion” implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.
others have described the problem, here is the solution (with cleaner test):
if(type.isInstance(next) {
return type.cast(next);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With