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));
What Does the “unchecked cast” Warning Mean? The “unchecked cast” is a compile-time warning. Simply put, we'll see this warning when casting a raw type to a parameterized type without type checking. An example can explain it straightforwardly.
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
Class.asSubclass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With