2017-08-06 71 views
1

我创建了一个这样的数组:Java的限制等级数组类型

Class<? extends AbstractItem>[] itemList = { 
      ItemNew.class, 
      ItemLoad.class, 
      ItemSave.class, 
      ItemSetting.class, 
      ItemEnd.class 
    }; 

java告诉我:

Cannot create a generic array of Class<? extends AbstractItem> 

如果我不指定类仿制药java警告我:

Class is a raw type. References to generic type Class<T> should be parameterized  

那么谁是正确的?甚至更多为什么它不允许我限制类的类型?

编辑:提到的重复不解决我的问题,如果我没有指定数组的类型,我可以用编译器警告创建它。所以这确实是可能的,但我正在寻找正确的方法来实现这一点)

+1

一般的经验法则:唐不结合泛型和数组。你只会头疼。 – Progman

+0

我可以创建它。如果我把它留给通用。但我担心编译器警告。对我来说,解决方案就是要解决这个问题,让我感到一种错误。 – Ranndom

+0

'List >类= Arrays.asList(ItemLoad.class,ItemNew.class);' –

回答

0

java不允许创建泛型数组,除非所有类型参数都是无界通配符。

考虑下面的代码:

List<String>[] strings=new List<String>[1]; //1 
    List<Integer> integers=Arrays.asList(1); 
    Object[] objects=strings; 
    objects[0]=integers; 
    String s=strings[0].get(0); 
    System.out.println(s);  //2 

查看语句1,如果用Java代码允许创建泛型类型数组,上面的代码会得到一个例外java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String上声明2 whitout任何警告在运行time.This是不正确的,所以Java不能创建泛型类型数组。

如果更改List<String>[] stringList=new List<String>[1]; //1List<String>[] stringList=new List[1];,代码将能够正确编译,但是编译器会产生警告像Unchecked assignment,当然,你可以使用@SuppressWarnings("unchecked")取消此警告。

JLS 10.6数组的初始化部分,有一个规则:

It is a compile-time error if the component type of the array being initialized is not reifiable 

JLS 4.7 Reifiable类型定义什么是reifiable types,第一个是:

It refers to a non-generic class or interface type declaration. 
+0

你描述的情况也出现了(在编译时)没有任何泛型(例如用String [],Object []和分配一个布尔值,它编译)。这是因为将一个Whatever []数组赋给一个声明为Object []的变量,甚至没有得到编译器警告。在非泛型情况下,至少在运行时会出现ArrayStoreException。 –