Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Snakybo Avatar asked Mar 08 '15 00:03

Snakybo


People also ask

How do I fix unchecked unchecked cast?

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.

What is an unchecked cast?

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.

What is unchecked warning?

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.

What is unchecked conversion in Java?

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.


1 Answers

others have described the problem, here is the solution (with cleaner test):

if(type.isInstance(next) {
  return type.cast(next);
}
like image 188
jtahlborn Avatar answered Sep 20 '22 14:09

jtahlborn