以下几行:
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中的兼容类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句