Java: How to determine if type is any of primitive/wrapper/String, or something else

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

The java.util.Class type has the proper methods:

Class<?> type = ...

boolean primitive = type.isPrimitive();
boolean string_ = type == String.class;
boolean array = type.isArray();
boolean enum_ = type.isEnum();
boolean interf_ = type.isInterface();

Tags:

Java

Types