views:

938

answers:

2

I am quite comfortable with generics and such, but in this special case I have a question concerning the "Type safety: Unchecked cast from .. to .." warning.

Basically I have a List of Class objects and now I want to get a subset of these that implement a special interface but the resulting List should also have that special Type:

...
private List<Class<?>> classes;

public List<Class<? extends Concrete>> getConcreteClasses() {

    List<Class<? extends Concrete>> concreteClasses = new LinkedList<Class<? extends Concrete>>();

    for (Class<?> clazz: this.classes) {
        for (Class<?> i : clazz.getInterfaces()) {
            if (i.equals(Concrete.class)) {
                concreteClasses.add((Class<? extends Concrete>) clazz);
            }
        }
    }

    return concreteClasses;

}

The warning is of course related to the type cast:

Type safety: Unchecked cast from Class<?> to Class<? extends Concrete>

Can I get rid of the type cast or should I suppress the warning with @SuppressWarnings("unchecked")?

Thanks for answers!

PS: The environment is Java 6.

Solution: Instead of

concreteClasses.add((Class<? extends Concrete>) clazz);

use

concreteClasses.add(clazz.asSubclass(Concrete.class));
+4  A: 

Class.asSubclass

Tom Hawtin - tackline
Thanks! Actually I already used asSubclass() in another piece of code....ooops :D
neo
Don't be surprised if you need to supress warnings elsewhere using reflection. (As ever, reflection is evil.)
Tom Hawtin - tackline
A: 

You can suppress the warnings, because you are sure the cast will work because all the classes you add implement the Concrete interface...

Fortega