简体   繁体   中英

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?

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>> 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM