Search code examples
javagenericstypescastingunchecked

Java Generics extends still generates unchecked cast warning


Is specifying the inheritance relation of parameterized generic types not enough to ensure type safety? For example:

public class ListCastFunction<F, T extends F> implements Function<F, T> {
    public final T apply(final F from) {
        return (T) from;
    }
}

This still generates a compiler warning. If we know T extends F, is it really unchecked?


Solution

  • You're casting and F to a T, but since T extends F, you're explicitly downcasting. There's no way to guarantee that the F given in the method is a T. Suppose I do this, assuming that the implied parent-child relationships are made:

    ListCastFunction<Animal, Mammal> lcf = new ListCastFunction<>;
    Mammal i = lcf.apply(new Fish());
    

    This would break when executed, because a Fish is not a Mammal, but it fits your code.