如何检查 class 是否代表特定的原始类型

How do I check if a class represents a particular primitive type

我需要确定特定的 class 是否是特定的原始类型,在我的例子中是 int。我找到了 Class.isPrimitive() 方法,但我不需要检查所有基元,我需要一个特定的基元。我注意到 class 名称等于原始名称,我考虑检查 candidateClass.getName().equals("int") - 但这似乎是一种不好的做法(和“魔术字符串”的使用)。

如何使用 Java API 正确检查特定的基本类型?

每个原始类型的每个包装器都提供一个静态字段,其中包含这些包装器的 类 个原始类型。例如:Integer.TYPE.

Class.isPrimitive 的文档提供了有关在 Java 中实现基本类型 类 的信息:

There are nine predefined Class objects to representthe 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.

部分代码供参考:

public class PrimitiveClassTest {
    static class Foo{
       public int a;
    }
    
    public static void main(String[] args) throws NoSuchFieldException, SecurityException {
        Class<?> intClass = Foo.class.getField("a").getType();
        System.out.println("obj.int field class: "+intClass);
        System.out.println("Integer.TYPE class:  "+Integer.TYPE);
        System.out.println("are they equal?      "+Integer.TYPE.equals(intClass));
    }
}

结果如下:

obj.int field class: int
Integer.TYPE class:  int
are they equal?      true

这可以大大简化为:

 intClass == int.class

这是可行的,因为 Class 文档说:

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.