java – Generics:为什么Class clazzIntArray = int [] .class;不起作用

以下行:

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和clazzInteger不相等.但是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无效?什么类< int []>手段?为什么数组和非数组类型之间的类比不起作用?

最佳答案 Autoboxing与它无关. Java语言规范指定(在
JLS 15.8.2中)T.class具有的类型:

>如果T是引用类型,则T.class具有类型Class< T>
>如果T是基本类型,则T.class具有类型Class

而已. int.class的类型为Class< Integer>因为规范是这样说的. int [] .class类型为Class< int []>因为规范是这样说的.类< INT [] GT;和类 是Java中不兼容的类型.

点赞