letmaik
letmaik

Reputation: 3500

Type safety: Unchecked cast between Class-Objects

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));

Upvotes: 9

Views: 5570

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Class.asSubclass

Upvotes: 10

Fortega
Fortega

Reputation: 19682

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

Upvotes: 0

Related Questions