gpt4 book ai didi

java - 如何检查一个类是否代表特定的原始类型

转载 作者:行者123 更新时间:2023-12-04 00:53:57 24 4
gpt4 key购买 nike

我需要确定一个特定的类是否是一个特定的原始类型,在我的例子中是一个int。我找到了 Class.isPrimitive() 方法,但我不需要检查所有基元,我需要一个特定的基元。我注意到类名等于原始名称,我考虑检查 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

关于java - 如何检查一个类是否代表特定的原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64155104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com