Java Reference
In-Depth Information
16.1. The
Class
Class
There is a
Class
object for every type. This includes each class, enum, in-
terface, annotation, array, and the primitive types. There is also a special
Class
object representing the keyword
void
. These objects can be used
for basic queries about the type and, for the reference types, to create
new objects of that type.
The
Class
class is the starting point for reflection. It also provides a tool to
manipulate classes, primarily for creating objects of types whose names
are specified by strings, and for loading classes using specialized tech-
niques, such as across the network. We look in more detail at class load-
ing in
Section 16.13
on page
435
.
You get a
Class
object in four ways: ask an object for its
Class
object us-
ing its
getClass
method; use a class literal (the name of the class followed
by
.class
, as in
String.class
); look it up by its fully qualified name (all
packages included) using the static method
Class.forName
; or get it from
one of the reflection methods that return
Class
objects for nested classes
and interfaces (such as
Class.getClasses
).
15.7.1. Type Tokens
Class is a generic class, declared as
Class<T>
. Each
Class
object for a ref-
erence type is of a parameterized type corresponding to the class it rep-
resents. For example, the type of
String.class
is
Class<String>
, the type
of
Integer.class
is
Class<Integer>
, and so forth. The type of the
Class
ob-
ject for a primitive type is the same type as that of its corresponding
wrapper class. For example, the type of
int.class
is
Class<Integer>
, but
note that
int.class
and
Integer.class
are two different instances of the
same type of class. Parameterized types all share the
Class
object of their
raw typefor example, the
Class
object for
List<Integer>
is the same as
that for
List<String>
and the same as that for
List.class
, and its type is
Class<List>
.