泛型投射问题 [英] Generics cast issue

查看:77
本文介绍了泛型投射问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的问题:给出这些类

  class A {} 
class B extends A {}

此代码编译:

 列表< Class< ;?延伸A>> list = Arrays.asList(B.class,A.class); 

这并不是:

  List< Class< ;?延伸A>> anotherList = Arrays.asList(B.class); 

给出了什么?






更新:这段代码在Java 8中编译。显然,由于'改进类型推断'。

在第一个例子中, Arrays.asList()调用的推断类型是 List< Class< ;?扩展A>> ,这显然可分配给相同类型的变量。在第二个示例中,右侧的类型边是列表< Class< B>> Class 可分配给 Class <?对< code>><>< / c $ c>< code>列表< ;类< ;?扩展A>> 。它可以分配给 List<扩展类<?这个原因与为什么 List< B> / code>不能分配给列表< A> 。如果是这样,它会使以下(非类型安全)代码成为可能:

  List< Class< B>> bb = new ArrayList< B>(); 
列表< Class< ;?延伸A>> aa = bb;
aa.add(A.class);


Here's my issue: given these classes

class A {}
class B extends A {}

This code compiles:

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

And this does not:

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

What gives?


UPDATE: This code compiles in Java 8. Apparently, due to 'Improved Type Inference'.

解决方案

In the first example, the inferred type of the Arrays.asList() call is List<Class<? extends A>>, which is obviously assignable to a variable of the same type.

In the second example, the type of the right side is List<Class<B>>. While Class<B> is assignable to Class<? extends A>, List<Class<B>> is not assignable to List<Class<? extends A>>. It would be assignable to List<? extends Class<? extends A>>.

The reason for this is the same one as why a List<B> isn't assignable to List<A>. If it was, it would make the following (not-typesafe) code possible:

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

这篇关于泛型投射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆