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<?> 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)