简体   繁体   English

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

[英]How do I check if a class represents a particular primitive type

I need to determine whether a specific class is a particular primitive type, an int in my case.我需要确定一个特定的类是否是一个特定的原始类型,在我的例子中是一个int I found Class.isPrimitive() method, but I don't need to check all primitives, I need a particular one.我找到了Class.isPrimitive()方法,但我不需要检查所有原语,我需要一个特定的。 I noticed that the class names are equal to primitive names and I considered checking for candidateClass.getName().equals("int") - but it seemed a bad practice (and a "magic string" use).我注意到类名等于原始名称,我考虑检查candidateClass.getName().equals("int") - 但这似乎是一种不好的做法(和“魔法字符串”的使用)。

How to check for a specific primitive type properly using Java API?如何使用 Java API 正确检查特定的原始类型?

Each wrapper for each primitive type provides a static field which contains classes of primitive types for those wrappers.每个基本类型的每个包装器都提供一个静态字段,其中包含这些包装器的基本类型类。 For example: Integer.TYPE .例如: Integer.TYPE

The documentation of Class.isPrimitive provides information about the implementation of primitive types classes in Java: Class.isPrimitive 的文档提供了有关 Java 中基本类型类实现的信息:

There are nine predefined Class objects to representthe eight primitive types and void.有九个预定义的 Class 对象来表示八种基本类型和 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.它们由 Java 虚拟机创建,并与它们所代表的原始类型具有相同的名称,即 boolean、byte、char、short、int、long、float 和 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.这些对象只能通过以下公共静态最终变量访问,并且是此方法为其返回 true 的唯一 Class 对象。

Some code for reference:一些代码供参考:

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));
    }
}

which gives the following results:这给出了以下结果:

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

This can be greatly simplified to:这可以大大简化为:

 intClass == int.class

This works because the Class documentation says:这是有效的,因为Class文档说:

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.原始 Java 类型(boolean、byte、char、short、int、long、float 和 double)和关键字 void 也表示为 Class 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM