Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

types

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.

like image 356
Ondra Žižka Avatar asked Jul 30 '14 14:07

Ondra Žižka


People also ask

How do you know if a given data type is primitive or not?

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.

How do you check if an object is primitive or not in Java?

The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.

Is string primitive or wrapper?

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.


2 Answers

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.

like image 57
Ondra Žižka Avatar answered Oct 06 '22 13:10

Ondra Žižka


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;
}
like image 24
Boann Avatar answered Oct 06 '22 14:10

Boann