Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generically tell if a Java Class is a primitive type?

Tags:

java

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.

like image 264
nathan Avatar asked Oct 16 '08 16:10

nathan


2 Answers

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;
  }
like image 152
kentcdodds Avatar answered Oct 14 '22 16:10

kentcdodds


There is a method on the Class object called isPrimitive.

like image 21
Dan Dyer Avatar answered Oct 14 '22 15:10

Dan Dyer