以下几行:
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[]>
方法?为什么数组和非数组类型之间的类比不起作用?
最佳答案
自动装箱与它无关。 Java 语言规范(在 JLS 15.8.2 中)明确指定了 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[]>
和 Class<Integer[]>
在 Java 中是不兼容的类型。
关于java - 泛型:为什么 Class<Integer[]> clazzIntArray = int[].class;不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982464/