13

Is there any way to take a Class and determine if it represents a primitive type (is there a solution that doesn't require specifically enumerating all the primitive types)?

NOTE: I've seen this question. I'm asking basically the opposite. I have the Class, I want to know if it's a primitive.

Community
  • 1
  • 1
nathan
  • 4,571
  • 2
  • 27
  • 28

3 Answers3

27

There is a method on the Class object called isPrimitive.

Hearen
  • 7,420
  • 4
  • 53
  • 63
Dan Dyer
  • 53,737
  • 19
  • 129
  • 165
7

Class.isPrimitive() will tell you the answer.

AdamC
  • 16,087
  • 8
  • 51
  • 67
2

This method will also check whether it's a wrapper of a primitive type as well:

/**
* Checks first whether it is primitive and then whether it's wrapper is a primitive wrapper. Returns true
* if either is true
*
* @param c
* @return whether it's a primitive type itself or it's a wrapper for a primitive type
*/
public static boolean isPrimitive(Class c) {
  if (c.isPrimitive()) {
    return true;
  } else if (c == Byte.class
          || c == Short.class
          || c == Integer.class
          || c == Long.class
          || c == Float.class
          || c == Double.class
          || c == Boolean.class
          || c == Character.class) {
    return true;
  } else {
    return false;
  }
kentcdodds
  • 27,113
  • 32
  • 108
  • 187
  • Use Number.class.isAssignableFrom(c) instead of checking equality with all Number subtypes – digital illusion Mar 22 '15 at 07:21
  • @digitalillusion That would also include non-wrapper types like `BigInteger`, which is a `Number` too – kapex Feb 10 '17 at 10:48
  • `return c.isPrimitive() || c.getSuperclass() == Number.class || c == Boolean.class || c == Character.class;` is an easier solution – GV_FiQst Jun 17 '17 at 13:54