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 ?
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.
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.
int. class is neither a superclass nor a subclass of 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With