Java 原生类型(primitive)对应的Class

我们知道Java中有8个基本原生类型

  • boolean
  • byte
  • char
  • double
  • float
  • int
  • long
  • short

boolean

byte

char

double

float

int

long

short

实际上8个基本类型,包括void返回类型在JDK中都对应了Class对象。以int为例,在Integer.java中可以看到下面的定义。

1
/**     * The {@code Class} instance representing the primitive type     * {@code int}.     *     * @since   JDK1.1     */    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
1
/**
1
* The {@code Class} instance representing the primitive type
1
* {@code int}.
1
*
1
* @since   JDK1.1
1
*/
1
public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

做一个简单的测试可以发现,int.class 和 Interger.TYPE 都是int对应的Class对象,它们是等价的。Interger.class不同,它是int的封装类型。

int.classInterger.TYPEint****Interger.class

1
package com.stone.javacore.primitive;public class TestPrimitive {    /**     * int.class 和 Interger.Type 是等价的,都是int对应的Class对象, 主要用在反射调用参数中     * Integer.class是int.class的wrapper类;int.class 是 primitive类     *     * @param args     */    public static void main(String[] args) {        Class c1 = int.class;        Class c2 = Integer.TYPE;        Class c3 = Integer.class;        System.out.println("c1 == c2 : " + (c1 == c2));        System.out.println("c1 == c3 : " + (c1 == c3));        System.out.println("c1 is primitive : " + c1.isPrimitive());        System.out.println("c2 is primitive : " + c2.isPrimitive());    }}
1
package com.stone.javacore.primitive;
1
public class TestPrimitive {
1
/**
1
* int.class 和 Interger.Type 是等价的,都是int对应的Class对象, 主要用在反射调用参数中
1
* Integer.class是int.class的wrapper类;int.class 是 primitive类
1
*
1
* @param args
1
*/
1
public static void main(String[] args) {
1
Class c1 = int.class;
1
Class c2 = Integer.TYPE;
1
Class c3 = Integer.class;
1
System.out.println("c1 == c2 : " + (c1 == c2));
1
System.out.println("c1 == c3 : " + (c1 == c3));
1
System.out.println("c1 is primitive : " + c1.isPrimitive());
1
System.out.println("c2 is primitive : " + c2.isPrimitive());
1
}
1
}

上面的测试程序的结果如下:

1
c1 == c2 : truec1 == c3 : falsec1 is primitive : truec2 is primitive : true
1
c1 == c2 : true
1
c1 == c3 : false
1
c1 is primitive : true
1
c2 is primitive : true

代码参考:https://github.com/shidongwa/TestPrj/blob/master/src/com/stone/javacore/primitive/TestPrimitive.java