PeterErnsthaft
PeterErnsthaft

Reputation: 395

incompatible types error when using generics and reflection

Let: B extends A;

Can somebody tell me why this code:

List<Class<? extends A>> l = Arrays.asList(B.class);

Throws me the following error when trying to compile:

error: incompatible types: List<Class<B>> cannot be converted to List<Class<? extends A>>

while this code:

ArrayList<Class<? extends A>> l = new ArrayList<Class<? extends A>>();
l.add(B.class);

works perfectly fine?

Upvotes: 0

Views: 545

Answers (1)

MaxZoom
MaxZoom

Reputation: 7753

As per documentation the Arrays.asList(..) method takes as its parameter variable(s) of the same type and returns the list of that type.

public static <T> List<T> asList(T... a)

If Class<B> is bond to type T then the method return type is List<Class<B>> which is NOT type List<Class<? extends A>> as expected. Thus the compile error occurs.

It can be fixed by adding the explicit cast as below:

List<Class<? extends A>> l = Arrays.<Class<? extends A>>asList(B.class);


EDITED
As mentioned by Sotirios Java 8 has resolved that tedious issue with introduction of poly expression explained here.

Upvotes: 2

Related Questions