Why a cast is necessary in this case?

Viewed 166

Let's say I have a method with the following signature:

public static <T> Set<Class<? extends T>> dosomething(Class<T> clazz)

If I tried to call this using a wildcard class, like in the example below

Class<?> clazz = Integer.class
Set<Class<?>> result = dosomething(clazz);

The compiler complains about the following:

Error: incompatible types: inference variable T has incompatible equality constraints java.lang.Object,capture#1 of ?

So the fix for that is to add a cast in the method call.

Set<Class<?>> result = (Set<Class<?>>) dosomething(clazz);

I am wondering why is that the cast is needed in this particular case and if there is any workaround to avoid casting... I am using java-8 for this. Thanks

1 Answers
Related