Java泛型 - 消失类型信息? [英] Java Generics - vanishing type information?

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

问题描述

好的 - 我知道Java泛型可能是一个不知情的雷区,但我刚刚遇到了一个非直观的(对我来说)行为,我想知道是否有人可以解释:首先,这里有一个类编译:

  public class Dummy {

public List< ;?扩展Number> getList(){
返回新的ArrayList< Number>();
}

public static void main(String [] args){
Dummy dummy = new Dummy();
for(Number n:dummy.getList()){
System.out.println(n);
}
}
}

简单的东西。现在,我通过向Dummy添加类型参数T来进行单个更改:

  public class Dummy< T> {

现在类无法编译,给出错误类型不匹配:无法转换()语句中的元素类型对象到数字

看起来,因为我已经参数化了Dummy类,所以创建新的Dummy()在主方法中(没有指定类型参数),将导致getList()方法的类型信息不再可用:编译器不再知道列表元素的类型,因此它们不能分配给循环Number类型的变量。为什么这种类型的信息缺失,因为< T>这个类的声明与< ;?完全没有关系扩展Number> getList()方法的声明?



此外,如果我现在将我的Dummy实例更改为:

 虚拟<?> dummy = new Dummy(); 

然后类型信息再次可用,并且类再次编译。那么为什么Dummy of unknown type允许保留其getList()类型信息,而Dummy(假定是未知类型,因为我没有指定参数)会丢失它?



也许我是假人: - ) 解决方案

总的想法是所有类型相关的信息都被擦除如果使用参数化类型的原始版本。这包括类类型参数所隐含的类型信息或者泛型方法参数。

非常类似的例子描述为这里


OK - I know that Java generics can be a minefield for the unwary, but I just came across a non-intuitive (to me anyway) behavior that I was wondering if anyone can explain: First of all, here's a class that compiles:

public class Dummy {

   public List<? extends Number> getList() {
      return new ArrayList<Number>();
   }

   public static void main(String[] args) {
      Dummy dummy = new Dummy();
      for (Number n: dummy.getList()) {
         System.out.println(n);
      }    
   }
}

Simple stuff. Now, I make a single change by adding a type parameter T to Dummy:

public class Dummy<T> {

Now the class fails to compile, giving the error "Type mismatch: cannot convert from element type Object to Number" on the for() statement

It appears that because I have parameterized the Dummy class, the creation of the new Dummy() in the main method (without specifying a type parameter), causes the type information for the getList() method to no longer be available: The compiler no longer knows the type of the list elements, so they can't be assigned to a loop variable of type Number. Why does this type information go missing, given that the <T> declaration on the class has nothing at all to do with the <? extends Number> declaration on the getList() method?

Furthermore, if I now change my instantiation of Dummy to be:

Dummy<?> dummy = new Dummy();

Then the type information becomes available again, and the class compiles once more. So why is a "Dummy of unknown type" allowed to retain its getList() type information whilst a Dummy (presumably of unknown type since I didn't specify a parameter) loses it?

Maybe I'm the Dummy :-)

解决方案

The general idea is that all type-related information is erased if you use raw version of parameterized type. That includes either type information implied by class type parameters or generic methods parameters as well.

Very similar example is described here.

这篇关于Java泛型 - 消失类型信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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