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