Search code examples
javaprimitive-types

How do I check if a class represents a particular primitive type


I need to determine whether a specific class is a particular primitive type, an int in my case. I found Class.isPrimitive() method, but I don't need to check all primitives, I need a particular one. I noticed that the class names are equal to primitive names and I considered checking for candidateClass.getName().equals("int") - but it seemed a bad practice (and a "magic string" use).

How to check for a specific primitive type properly using Java API?


Solution

  • This can be greatly simplified to:

     intClass == int.class
    

    This works because the Class documentation says:

    The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.