Skip to content
Advertisement

Is it possible to return the Class of a generic type without any warning?

The question is pretty simple, take a look at the following code:

public class ChoiceBox<T> {}

public Class<ChoiceBox> getApplicableClass() {
        return ChoiceBox.class;
}

In eclipse and maybe other ide, a warning is generated:

ChoiceBox is a raw type. References to generic type ChoiceBox<T> should be parameterized

So i did change the return type of the getApplicableClass function to:

public Class<ChoiceBox<?>> getApplicableClass()

But the question now is, how can i return a Class<ChoiceBox<?>> without warning

public Class<ChoiceBox<?>> getApplicableClass() {
    return ??????????????;
}

Advertisement

Answer

This case is explicitly treated in the book Effective Java by Joshua Bloch.

There are a few minor exceptions to the rule that you should not use raw types. You must use raw types in class literals. The specification does not permit the use of parameterized types [in class literals].

The answer to your question is: No, it’s not possible to avoid a warning in this case unless you use a @SuppressWarnings("unchecked") annotation.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement