Reputation: 22241
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?
Upvotes: 3
Views: 112
Reputation: 120848
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.
Upvotes: 1
Reputation: 22241
Each wrapper for each primitive type provides a static field which contains classes of primitive types for those wrappers. For example: Integer.TYPE
.
The documentation of Class.isPrimitive provides information about the implementation of primitive types classes in Java:
There are nine predefined Class objects to representthe eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double. These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.
Some code for reference:
public class PrimitiveClassTest {
static class Foo{
public int a;
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
Class<?> intClass = Foo.class.getField("a").getType();
System.out.println("obj.int field class: "+intClass);
System.out.println("Integer.TYPE class: "+Integer.TYPE);
System.out.println("are they equal? "+Integer.TYPE.equals(intClass));
}
}
which gives the following results:
obj.int field class: int
Integer.TYPE class: int
are they equal? true
Upvotes: 5