Why is the action necessary in this case?

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 this is to add a cast to the method call.

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

      

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

+3


source to share


1 answer


The problem is the parameter of the substitution type in Set<Class<?>> result

, whereas your method returnsSet<Class<? extends T>>

So the result can contain Class-Objects of any type (subtypes of Object), the method only returns objects that are subtypes of T (as indicated in the compiler error).

Either it

public static void main(String[] args) {
    Class<?> clazz = Integer.class;
    Set<Class<?>> result = dosomething(clazz);
}

public static <T> Set<Class<?>> dosomething(Class<T> clazz){
    return new HashSet<Class<?>>();
}

      



or

public static void main(String[] args) {
    Class<Integer> clazz = Integer.class;
    Set<Class<? extends Integer>> result = dosomething(clazz);
}

public static <T> Set<Class<? extends T>> dosomething(Class<T> clazz){
    return new HashSet<Class<? extends T>>();
}

      

will work without error.

In your code, due to type erasure, the compiler cannot be sure that your code is correct at runtime and therefore complains.

+1


source







All Articles