Java Reference
In-Depth Information
The method
getName()
is a member of the class
Class
which returns the fully qualified name of the
class as a
String
object - the second statement will output the name of the class for the
pet
object. If
pet
referred to a
Duck
object this would output:
Duck
This is the fully qualified name in this case as the class is in the default package, which has no name. For
a class defined in a named package the class name would be prefixed with the package name. If you just
wanted to output the class identity you need not explicitly store the
Class
object. You can combine
both statements into one:
System.out.println(pet.getClass().getName()); // Output the class name
This will produce the same output as before.
Members of the Class class
When your program is executing there are instances of the class
Class
representing each of the classes
and interfaces in your program. The Java Virtual Machine generates these when your program is
loaded. Since
Class
is intended for use by the Java Virtual Machine, it has no public constructors, so
you can't create objects of type
Class
yourself.
Class
defines a lot of methods, but most of them are not relevant in normal programs. The primary
use you will have for
Class
is obtaining the class of an object by calling the
getClass()
method for
the object as we have just discussed. However, you also get a number of other useful methods with an
object of class
Class
:
Method
Purpose
forName()
You can get the
Class
object for a known class type with this method.
You pass the name of the class as a
String
object to this method, and it
returns a
Class
object for the class that has the name you have supplied. If
no class of the type you specify exists, a
ClassNotFoundException
exception will be thrown. You can use this method to test whether an
object is of a particular class type.
newInstance()
This method will call the default constructor for the class, represented by
the current
Class
object, and will return the object created as type
Object
. Unless you want to store the result in a variable of type
Object
,
you must cast the object to the appropriate type. When things don't work as
they should, this method can throw two exceptions -
InstantiationException
or
IllegalAccessException
.
If you use this method and don't provide for handling the exceptions, your
program will not compile. We'll learn how to deal with this in the next
chapter.
Table continued on following page