Java Reference
In-Depth Information
Table 3-2.
Class Literals for Primitive Data Types and the void Keyword
Data Type
Primitive Class Literal
Wrapper Class Static Field
boolean
boolean.class
Boolean.TYPE
byte
byte.class
Byte.TYPE
char
char.class
Character.TYPE
short
short.class
Short.TYPE
int
int.class
Integer.TYPE
long
long.class
Long.TYPE
float
float.class
Float.TYPE
double
double.class
Double.TYPE
void
void.class
Void.TYPE
The
Object
class has a
getClass()
method, which returns the reference to the
Class
object of the class of the
object. This method is available in every class in Java because every class in Java, explicitly or implicitly, inherits
Object
class. The method is declared
final
, so no descendant class can override it. For example, if you have
testRef
as a reference to an object of class
Test
, you can get the reference to the
Class
object of the
Test
class as follows:
Test testRef = new Test();
Class<Test> testClass = testRef.getClass();
The
Class
class has a
forName()
static method which returns a reference to a
Class
object. It is an overloaded
method The declarations of the two overloaded versions of this method are
Class<?> forName(String className)
•
Class<?> forName(String name, boolean initialize, ClassLoader loader)
The first version of the
forName()
method takes an argument, which is the fully qualified name of the class to
be loaded. It loads the class, initializes it, and returns the reference to its
Class
object. If the class is already loaded,
it simply returns the reference to the
Class
object of that class. The second version of this method gives you the
option to initialize or not to initialize the class when it is loaded, and which class loader should load the class. Both
methods throw a
ClassNotFoundException
if the class could not be loaded. To load a class named
pkg1.Test
, you
would write
•
Class testClass = Class.forName("pkg1.Test");
To get a
Class
object reference using the
Class.forName()
method, you do not have to know the name of the
class until runtime. The
forName(String className)
method initializes the class if it is not already initialized,
whereas the use of a class literal does not initialize the class. Prior to Java 5, a class was initialized when you used its
class literal. Java 5 does not initialize the class when you use its class literal. When a class is initialized, all its static
initializers are executed and all static fields are initialized. Listing 3-1 lists a
Bulb
class with only one static initializer,
which prints a message on the console. Listing 3-2 uses various methods to load and initialize the
Bulb
class.