I really like generics, etc., but in this special case I have a question regarding a warning like "Type: Unchecked cast from .. to ..".
Basically, I have objects of class Class, and now I want to get a subset of them that implement a special interface, but the resulting List should also have a 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, of course, is related to the cast type:
Type safety: Unchecked cast from Class<?> to Class<? extends Concrete>
Can I get rid of the cast type or should I suppress the warning with @SuppressWarnings ("unchecked")?
Thanks for answers!
PS: environment is Java 6.
Solution: Instead
concreteClasses.add((Class<? extends Concrete>) clazz);
using
concreteClasses.add(clazz.asSubclass(Concrete.class));
source
share