Is there a single method in JDK or common basic libraries which returns true if a type is a primitive, a primitive wrapper, or a String?
I.e.
Class<?> type = ...
boolean isSimple = SomeUtil.isSimple( type );
The need for such information can be e.g. to check whether some data can be represented in formats like JSON. The reason for a single method is to be able to use it in expression language or templates.
To check a value whether it is primitive or not we use the following approaches: Approach 1: In this approach, we check the type of the value using the typeof operator. If the type of the value is 'object' or 'function' then the value is not primitive otherwise the value is primitive.
The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string.
I found something:
Commons Lang: (would have to combine with check for String)
ClassUtils.isPrimitiveOrWrapper()
Spring:
BeanUtils.isSimpleValueType()
This is what I want, but would like to have it in Commons.
Is there a single method which returns true if a type is a primitive
Class.isPrimitive:
Class<?> type = ...;
if (type.isPrimitive()) { ... }
Note that void.class.isPrimitive()
is true too, which may or may not be what you want.
a primitive wrapper?
No, but there are only eight of them, so you can check for them explicitly:
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) { ... }
a String?
Simply:
if (type == String.class) { ... }
That's not one method. I want to determine whether it's one of those named or something else, in one method.
Okay. How about:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With