Java:如何确定type是否是primitive/wrapper/String或其他内容

Ond*_*žka 14 java types

JDK或公共基本库中是否有单个方法,如果类型是基元,基元包装器或字符串,则返回true?

Class<?> type = ...
boolean isSimple = SomeUtil.isSimple( type );
Run Code Online (Sandbox Code Playgroud)

对此类信息的需求可以是例如检查某些数据是否可以以诸如JSON的格式表示.单个方法的原因是能够在表达式语言或模板中使用它.

Ond*_*žka 22

我发现了一些东西

Commons Lang :(必须结合检查字符串)

ClassUtils.isPrimitiveOrWrapper()
Run Code Online (Sandbox Code Playgroud)

春天:

BeanUtils.isSimpleValueType()
Run Code Online (Sandbox Code Playgroud)

这就是我想要的,但是想在Commons中拥有它.


Boa*_*ann 18

是否有一个方法,如果类型是基元,则返回true

Class.isPrimitive:

Class<?> type = ...;
if (type.isPrimitive()) { ... }
Run Code Online (Sandbox Code Playgroud)

请注意,这void.class.isPrimitive()也是正确的,可能是也可能不是您想要的.

一个原始的包装?

不,但只有八个,所以你可以明确地检查它们:

if (type == Double.class || type == Float.class || type == Long.class ||
    type == Integer.class || type == Short.class || type == Character.class ||
    type == Byte.class || type == Boolean.class) { ... }
Run Code Online (Sandbox Code Playgroud)

一个字符串?

只是:

if (type == String.class) { ... }
Run Code Online (Sandbox Code Playgroud)

那不是一种方法.我想在一种方法中确定它是否是其中一个名称或其他东西.

好的.怎么样:

public static boolean isPrimitiveOrPrimitiveWrapperOrString(Class<?> type) {
    return (type.isPrimitive() && type != void.class) ||
        type == Double.class || type == Float.class || type == Long.class ||
        type == Integer.class || type == Short.class || type == Character.class ||
        type == Byte.class || type == Boolean.class || type == String.class;
}
Run Code Online (Sandbox Code Playgroud)

  • @StevePitchers Java语言规范[明确定义了八种基本类型](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2)."BigInteger"和朋友是引用类型(而且非常复杂!),尽管它们的目的是通过不可变的方式像基元一样运行.实际上,不变性被打破了,因为他们忘了让这些课程"最终"."类似原始"引用类型的更好候选者是`String`,或者是["基于值的"](https://docs.oracle.com/javase/8/docs/api/java/lang/ doc-files/ValueBased.html)类,如`Optional`. (3认同)