Java Reference
In-Depth Information
You also can create
Class
objects by using the
forName()
class method with a single
argument: a string containing the name of an existing class. The following statement cre-
ates a
Class
object representing a
JLabel
, one of the classes of the
javax.swing
pack-
age:
Class lab = Class.forName(“javax.swing.JLabel”);
The
forName()
method throws a
ClassNotFoundException
if the specified class cannot
be found, so you must call
forName()
within a
try
-
catch
block or handle it in some
other manner.
To retrieve a string containing the name of a class represented by a
Class
object, call
getName()
on that object. For classes and interfaces, this name includes the name of the
class and a reference to the package to which it belongs. For primitive types, the name
corresponds to the type's name (such as
int
,
float
, or
double
).
Class
objects that represent arrays are handled a little differently when
getName()
is
called on them. The name begins with one left bracket character (“[“) for each dimension
of the array;
float[]
would begin with “[“,
int[][]
with “[[“,
KeyClass[][][]
with
“[[[“, and so on.
If the array is of a primitive type, the next part of the name is a single character repre-
senting the type, as shown in Table 16.1.
TABLE 16.1
Type Identification for Primitive Types
Character
Primitive Type
B
byte
C
char
D
double
F
float
I
int
J
long
S
short
Z
boolean
For arrays of objects, the brackets are followed by an
L
and the name of the class. For
example, if you called
getName()
on a
String[][]
array, the result would be
[[Ljava.lang.String
.