泛型通配符实例化 [英] Generics wildcard instantiation

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

问题描述

我有一天正在审查别人的代码,并且遇到了一条引起关注的线路。为了简化,假设我有一个泛型类A和一个抽象类B.是否允许下面的实例化,如果是这样,为什么?

  Object obj = new A< ;?扩展B>(); 

我个人从来没有见过像上面那样的实例,尽管声明如

  A <?扩展B> obj = null; 

肯定会成立。我一直使用泛型中的通配符来声明方法参数,所以我可能只是没有经验。

解决方案

其实新的A< ;?扩展B>()不能编译。自从Java 5以来,它一直是非法的。



但我想你的原始示例是类似于 new A< X<扩展B>>()。后者在最近版本的Java中是合法的。



这个想法是,在实例化对象时,类型参数的值可以是任何非通配符类型。 ?扩展B 是通配符类型,因此不允许使用。但 X <?扩展B> 不是通配符类型,尽管它具有通配符类型作为组件。所以你可以合法地称呼新的A< X<如果你这样想的话,这些规则是有意义的。最终它是更基本规则的副产品,像这样的通配符类型?扩展B 不能是字段或变量的声明类型。如果 A 定义为

  class A< T> {
T值;
}

然后是假设的 new A< ;?扩展B>()。value 将是一个声明为 类型的字段。扩展B 。既然这是非法的,那么实例化也是非法的。但新的A< X<扩展B>>()没有这个问题。


I was reviewing someone else's code the other day and I came across a line that raised some concern. To simplify, say I have a generic Class A and an abstract Class B. Is the following instantiation allowed and if so, why?

Object obj = new A<? extends B>();

I personally have never seen an instantiation like the above, although a declaration such as

A<? extends B> obj = null;

would certainly hold. I've always used the wildcard in generics to declare method parameters, so I may just not have the experience.

解决方案

Actually new A<? extends B>() does not compile. It has been consistently illegal since Java 5.

But I guess your original example was something like new A<X<? extends B>>(). The latter is legal in recent versions of Java.

The idea is, when instantiating an object, the value for type parameters can be any non-wildcard type. ? extends B is a wildcard type, so it is disallowed. But X<? extends B> is not a wildcard type, though it has a wildcard type as a component. So you can say legally call new A<X<? extends B>>().

The rules makes sense if you think about it this way. Ultimately it is a byproduct of the more fundamental rule that a wildcard type like ? extends B cannot be the declared type of a field or variable. If A is defined as

class A<T> {
    T value;
}

then the hypothetical new A<? extends B>().value would be a field declared of type ? extends B. Since that is illegal, so is the instantiation. But new A<X<? extends B>>() does not have that problem.

这篇关于泛型通配符实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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