Java Reference
In-Depth Information
You also can use the
Class
class to create new objects. Call the
newInstance()
method
on a
Class
object to create the object and cast it to the correct class.
For example, if you have a
Class
object named
thr
that represents the
Throwable
inter-
face, you can create a new object as follows:
Throwable thr2 = (Throwable)thr.newInstance();
The
newInstance()
method throws several kinds of exceptions:
IllegalAccessException
—You do not have access to the class either because it is
not
public
or because it belongs to a different package.
n
16
InstantiationException
—You cannot create a new object because the class is
abstract.
n
SecurityViolation
—You do not have permission to create an object of this class.
n
When
newInstance()
is called and no exceptions are thrown, the new object is created
by calling the constructor of the corresponding class with no arguments.
You cannot use this technique to create a new object that requires
arguments to its constructor method. Instead, you must use a
newInstance()
method of the
Constructor
class, as you will see
later today.
NOTE
Working with Each Part of a Class
Although
Class
is part of the
java.lang
package, the primary support for reflection is
the
java.lang.reflect
package, which includes the following classes:
Field
—Manages and finds information about class and instance variables
n
Method
—Manages class and instance methods
n
Constructor
—Manages constructors, the special methods for creating new
instances of classes
n
Array
—Manages arrays
n
Modifier
—Decodes modifier information about classes, variables, and methods
(which were described on Day 6, “Packages, Interfaces, and Other Class Features”)
n