int.class的目的和功能是什么

时间:2015-01-31 19:22:20

标签: java

我意外地发现这有效:

Class<?> a;

a = int.class;
System.out.println(a); // int

a = Integer.class;      
System.out.println(a); // class java.lang.Integer

它对原语的真正含义是什么?

我试过,List<int>List<int.class>都没有用(是的,我知道我必须使用整数)。另外,显然,我无法在原语上调用getClass(),因此它对任何类型的类型检查都没用。

在什么情况下我会使用int.class,为什么它甚至会出现在语言中?

2 个答案:

答案 0 :(得分:4)

当您尝试通过反射API找到具有int参数的方法时,可以使用它。

答案 1 :(得分:1)

来自规格:

The type of p.class, where p is the name of a primitive type 
(§4.2), is Class<B>, where B is the type of an expression of 
type p after boxing conversion (§5.1.7).

A class literal evaluates to the Class object for the named 
type (or for void) as defined by the defining class loader 
(§12.2) of the class of the current instance.

那怎么样?

Class<Integer> a = int.class;

何时使用:大量反射用例(例如在argparse4j中,它们使用它从命令行参数映射到方法)。