泛型:为什么Class <integer []> clazzIntArray = int [] .class;不起作用

时间:2015-08-13 07:49:55

标签: java arrays generics

以下行:

Class<Integer> clazzInteger = Integer.class;
Class<Integer> clazzInt = int.class;

有效且即使在以下情况下也会编译/运行:

if(clazzInt.equals(clazzInteger)) {
  System.out.println("clazzInt equals clazzInteger");
}else {
  System.out.println("clazzInt and clazzInteger are not equal");
}

将打印clazzInt and clazzInteger are not equal。但Class<int> clazzInt = int.class;当然不起作用。

那么为什么这个类比不能应用于数组类型?

Class<int[]> clazzIntArray = int[].class;
Class<Integer[]> clazzIntArray = int[].class;  // type mismatch: 
//cannot convert from Class<int[]> to Class<Integer[]>

但是

Class<int[]> clazzIntArray = int[].class; // this is ok 

我现在感到困惑,为什么Class<Integer[]> clazzIntArray = int[].class无效? Class<int[]>的含义是什么?为什么数组和非数组类型之间的类比不起作用?

3 个答案:

答案 0 :(得分:1)

引擎盖下,Autoboxing/Unboxing发生在数组内的各个元素上。不是整个数组类型。

Java无法将整个原始数组神奇地转换为Wrapper数组。这里有一个单独的元素和一个由各个元素组成的数组。

例如:数组是篮子,篮子里面的水果是元素(int's / Integer's)

答案 1 :(得分:1)

Autoboxing与它无关。 Java语言规范(JLS 15.8.2)确切地指出了 public partial class Article { public Article() { Authors = new HashSet<Author>(); } [DisplayName("Авторы")] public virtual ICollection<Author> Authors { get; set; } 具有的类型:

  • 如果T.class是参考类型,则T的类型为T.class
  • 如果Class<T>是基本类型,则T的类型为T.class

那就是它。 Class<wrapper class of T>的类型为int.class,因为规范是这样说的。 Class<Integer>的类型为int[].class,因为规范是这样说的。 Class<int[]>Class<int[]>不是Java中的兼容类型。

答案 2 :(得分:0)

自动装箱仅适用于单个&#34;实例&#34; - int可以自动装箱到Integer,而Integer可以开箱到int。但是对于数组来说并非如此。例如,语句int[] arr = new Integer[10];将无法编译。这同样适用于通过反射来操纵这些类。