Search code examples
javareferenceprimitive

What does int.class mean


In java int, float and etc., are primitive types. Wrapper classes are used in case we need to use it with generics. But still the following declaration works in java,

 Class<Integer> intClass=int.class

How can we call int.class even though it is a primitive type?


Solution

  • A primitive becoming an Object

    For primitives, there are Class objects available as constants named TYPE in the corresponding wrapper classes -- i.e. int.class is changed to java.lang.Integer.TYPE . For other types, the compiler creates a private member variable in the class being compiled to hold the Class object, and generates code to initialize that member using Class.forName() .

    Found some discussion

    And a nice discussion here and your example also covered in this link.

    A few words from there :

    how can a Class be a primitive? Let's confuse things a bit more. We can access the Class object representing a defined class by coding, say:

    Equation.class // returns the Equation Class object
    

    But, we can also say:

    int.class
    

    obtain a Class object whose name is "int". Note we have not sent the getClass() method to an object; we have used the reserved word for a built-in primitive type (int) and, using dot notation, accessed its class "field." And this returns a Class object!