Access to a call object representing a primitive type

I read that to access the call object representing a primitive type, I can do this:

Class intClass = int.class; 

But how do primitive types have classes for representing them? They are primitive, which means they have no class. Why does the above example work, and which class contains an int (possibly an Integer class)?

+5
source share
3 answers

Like javadoc for class class states

Class instances represent classes and interfaces in a running Java application. enum is a kind of class and annotation is a kind of interface. Each array also belongs to a class, which is reflected as a Class object, which is shared by all arrays with the same element type and number of dimensions. Primitive Java types ( boolean , byte , char , short , int , long , float and double ), and the void keyword are also represented as Class objects.

The A Class object simply provides some metadata and factory methods for the type it represents.

For example, Class#isPrimitive() will tell you if the type represented is primitive.

The Class class and its instances, among other things, are used for reflection.

Say you had a class like

 public class Example { public long add(int first, long second) { // for whatever reason return first + second; } } 

and you want to call the add method, considering only its name and parameter types. Failed to complete the following:

 Class<?> exampleClass = Example.class; exampleClass.getMethod("add", Integer.class, Long.class); 

because the parameter types are not Integer and long , they are int and long .

You will need to do something like

 Class<Example> exampleClass = Example.class; Method addMethod = exampleClass.getMethod("add", int.class, long.class); Example instance = exampleClass.newInstance(); addMethod.invoke(instance, 42, 58L); 
+7
source

If you look at the field summary for the Integer class, you will find that the primitive int type is actually represented by an instance of the TYPE class. Therefore, int.class will be equal to Integer.TYPE .

Here's a link to Javadocs where you can find an instance of the TYPE class.

+4
source

When you type int.class you get the corresponding wrapper class of the object that each primitive has. For more information, read the Java tutorials for autoboxing and look at each primitive corresponding wrapper class.

0
source

All Articles