Java Reference
In-Depth Information
methodonanobjectreference;forexample,
Employee e = new Employee();
Class<? extends Employee> clazz = e.getClass();
. The
getClass()
method does not throw an exception because the class from which the
object was created is already present in memory.
There is one more way to obtain a
Class
object, and that is to employ a
class
literal
,whichisanexpressionconsistingofaclassname,followedbyaperiodseparator,
followed by reserved word
class
. Examples of class literals include
Class<Em-
ployee> clazz = Employee.class;
and
Class<String> clazz =
String.class
.
Perhaps you are wondering about how to choose between
forName()
,
getClass()
, and a class literal. To help you make your choice, the following list
compares each competitor:
•
forName()
isveryflexibleinthatyoucandynamicallyspecifyanyreference
type by its package-qualified name. If the type is not in memory, it is loaded,
linked, and initialized. However, lack of compile-time type safety can lead to
runtime failures.
•
getClass()
returns a
Class
object describing the type of its referenced
object. If called on a superclass variable containing a subclass instance, a
Class
objectrepresentingthesubclasstypeisreturned.Becausetheclassisin
memory, type safety is assured.
• Aclassliteralreturnsa
Class
objectrepresentingitsspecifiedclass.Classlit-
eralsarecompactandthecompilerenforcestypesafetybyrefusingtocompile
the source code when it cannot locate the literal's specified class.
Note
You can use class literals with primitive types, including
void
. Examples
include
int.class
,
double.class
, and
void.class
. The returned
Class
object represents the class identified by a primitive type wrapper class's
TYPE
field
or
java.lang.Void.TYPE
. For example, each of
int.class == In-
teger.TYPE
and
void.class == Void.TYPE
evaluates to true.
You can also use class literals with primitive type-based arrays. Examples include
int[].class
and
double[].class
. For these examples, the returned
Class
objects represent
Class<int[]>
and
Class<double[]>
.