Search code examples
javatype-parameterunchecked-cast

Java unchecked cast to type parameter warning despite being instance of


Consider you have this List:

private final List<? extends AbstractXmlElement> inMemoryElements;

that contains a bunch of objects of subclasses of AbstractXmlElement and you want to add a method to filter objects of a specific subclass from that list. For this I created the following method:

public <E extends AbstractXmlElement> List<E> getInstancesOf(Class<E> c) {
    return getUsableElements().stream()
        .filter(c::isInstance)
        .map(e -> (E) e)
        .collect(Collectors.toList());
}

Yet (E) e results in an UncheckedCast Warning. I was wondering how exactly this is an unchecked cast and if it is safe to suppress this warning since those objects that are not an instance of E are filtered out before the cast. Meaning that, as far as I know, the cast should never fail


Solution

  • It's an unchecked cast because the type of E is unknown at runtime. Since you're checking isInstance(), your code is safe. But if you want to avoid the warning, you can use c to do the cast:

    .map(c::cast)