Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 265
letmaik Avatar asked May 21 '09 11:05

letmaik


People also ask

What is unchecked type cast?

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.

What are unchecked warnings in Java?

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.


1 Answers

Class.asSubclass

like image 75
Tom Hawtin - tackline Avatar answered Sep 22 '22 09:09

Tom Hawtin - tackline