|
|
Examining Classes |
To create an instance of a class, you invoke a special method called a constructor. Like methods, constructors can be overloaded, and are distinguished from one another by their signatures.You can get information about a class's constructors by invoking the
getConstructorsmethod, which returns an array ofConstructorobjects. Using the methods provided by theConstructorclass, you can determine the constructor's name, set of modifiers, parameter types, and set of throwable exceptions. You can also create a new instance of the
Constructorobject's class with theConstructor.newInstancemethod. You'll learn how to invokeConstructor.newInstancein Manipulating Objects.The sample program that follows prints out the parameter types for each constructor in the
Rectangleclass. The program performs the following steps:
- It retrieves an array of
Constructorobjects from theClassobject by callinggetConstructors.- For every element in the
Constructorarray, it creates an array ofClassobjects by invokinggetParameterTypes. TheClassobjects in the array represent the parameters of the constructor.- By calling
getName, the program fetches the class name for every parameter in theClassarray created in the preceding step.It's not as complicated as it sounds. Here's the source code for the sample program:
In the first line of output generated by the sample program, no parameter types appear because that particularimport java.lang.reflect.*; import java.awt.*; class SampleConstructor { public static void main(String[] args) { Rectangle r = new Rectangle(); showConstructors(r); } static void showConstructors(Object o) { Class c = o.getClass(); Constructor[] theConstructors = c.getConstructors(); for (int i = 0; i < theConstructors.length; i++) { System.out.print("( "); Class[] parameterTypes = theConstructors[i].getParameterTypes(); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(parameterString + " "); } System.out.println(")"); } } }Constructorobject represents a no-argument constructor. In subsequent lines, the parameters listed are eitherinttypes or fully-qualified object names. The output of the sample program is as follows:( ) ( int int ) ( int int int int ) ( java.awt.Dimension ) ( java.awt.Point ) ( java.awt.Point java.awt.Dimension ) ( java.awt.Rectangle )
|
|
Examining Classes |