谈论 Java (7),您可以获得一个基本类型的类,如下所示:
Class classOfInt = int.class
对于每一个,您都会得到一个名为原始类型的“类”:
int.class --> int
byte.class --> byte
double.class --> double
...
但是您无法创建这些实例:
char.class.newInstance(); // throws 'InstantiationException'
看来它们的类没有映射到相应的包装类(Integer
, Byte
, etc.).
那么它们为什么有“类”,它们是如何使用以及如何实现的呢?
它们用于反射。
Method round = Math.class.getMethod("round", double.class);
System.out.println(Arrays.toString(round.getParameterTypes()));
System.out.println(round.getReturnType() == long.class);
Method exit = System.class.getMethod("exit", int.class);
System.out.println(Arrays.toString(exit.getParameterTypes()));
System.out.println(exit.getReturnType() == void.class);
prints
[double]
true
[int]
true
它们是如何实施的?
它们是内置于 JVM 中的,没有类文件来定义它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)