Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 424
Dariusz Avatar asked Nov 26 '25 09:11

Dariusz


2 Answers

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
like image 173
Dariusz Avatar answered Nov 27 '25 23:11

Dariusz


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.

like image 21
Eugene Avatar answered Nov 27 '25 22:11

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!