java:Class的isPrimitive方法使用
1 前言
java中Class类的isPrimitive方法,用于检查类型是否为基本类型。java虚拟机创建了int、byte、short、long、float、double、boolean、char这8种基础信息,以及void,一共9种。为这9种类型时,isPrimitive方法将返回true,反之返回false。
参考java api文档说明:
Determines if the specified Class object represents a primitive type.
There are nine predefined Class objects to represent the eight primitive types and void.
These are created by the Java Virtual Machine,
and have the same names as the primitive types that they represent,
namely boolean, byte, char, short, int, long, float, and double.
These objects may only be accessed via the following public static final variables,
and are the only Class objects for which this method returns true.
Returns:
true if and only if this class represents a primitive type
Since:
JDK1.1
See Also:
Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE
2 使用
public static void isPrimitive(){
System.out.println(Boolean.TRUE.getClass().isPrimitive());
System.out.println(TestAsync.class.isPrimitive());
Class<?> a = new Integer(1).getClass();
System.out.println(a.isPrimitive());
System.out.println("*******************");
System.out.println(int.class.isPrimitive());
System.out.println(byte.class.isPrimitive());
System.out.println(short.class.isPrimitive());
System.out.println(long.class.isPrimitive());
System.out.println(float.class.isPrimitive());
System.out.println(double.class.isPrimitive());
System.out.println(boolean.class.isPrimitive());
System.out.println(char.class.isPrimitive());
System.out.println(void.class.isPrimitive());
}
执行结果:
false
false
false
*******************
true
true
true
true
true
true
true
true
true