Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is contained in int.class in Java ?Why is it even valid?

Tags:

java

In Java it is valid to have a class literal for primitives like int.class. Was this allowed even prior to the introduction of auto boxing feature in Java ? What does the object that we get out of int.class contain actually ? Why is it valid ?

like image 808
Geek Avatar asked Feb 18 '13 18:02

Geek


People also ask

What type of class is int?

For instance int is the primitive type and Integer the class type. When you use generics, you are forced to use a non-primitive type so ArrayList<Integer> is allowed but ArrayList<int> not.

Is int a class Java?

Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa. An object of the Integer class can hold a single int value.

Is int a subclass of Integer?

int. class is neither a superclass nor a subclass of Integer.

Is it better to use int or Integer?

int provides less flexibility as compare to Integer as it only allows binary value of an integer in it. Integer on other hand is more flexible in storing and manipulating an int data. Since Wrapper classes inherit Object class, they can be used in collections with Object reference or generics.


2 Answers

int is not a class, so int.class doesn't really make sense.

The reason is they went cheap, and used one Class to represent all types. So for example, Method.getReturnType() returns a Class, which could actually represent a class, or a primitive, an array, or even void.

That was sort of fine, before generics, since there weren't too many kinds of types. After generics, things get really messy, the new Type hierarchy makes even less sense, since it incorporates the old messy Class; as a result the tree of Types looks nothing like the tree of types in the language spec.

like image 130
irreputable Avatar answered Oct 28 '22 16:10

irreputable


yes, it is a key part of reflection (e.g. describing a method which takes an int parameter). there is a Void class as well.

like image 32
jtahlborn Avatar answered Oct 28 '22 15:10

jtahlborn