Java Reference
In-Depth Information
The MethodInspector application displays information about the public methods in the
class you specify at the command line (or MethodInspector itself, if you don't specify a
class). To try the program, enter the following at a command line:
java MethodInspector java.util.Random
If you run the application on the java.util.Random class, the program's output is the
following (with some methods omitted):
Method: writeObject()
Modifiers: private synchronized
Return Type: void
Parameters: java.io.ObjectOutputStream
Method: next()
Modifiers: protected
Return Type: int
Parameters: int
...
Method: setSeed()
Modifiers: public synchronized
Return Type: void
Parameters: long
By using reflection, the MethodInspector application can learn every method of a class.
A Class object is created in lines 7-10 of the application. If a class name is specified as
a command-line argument when MethodInspector is run, the Class.forName() method
is called with that argument. Otherwise, MethodInspector is used as the argument.
After the Class object is created, its getDeclaredMethods() method is used in line 11 to
find all the methods contained in the class (with the exception of methods inherited from
a superclass). These methods are stored as an array of Method objects.
The for loop in lines 12-28 cycles through each method in the class, storing its return
type, modifiers, and arguments and then displaying them.
Displaying the return type is straightforward: Each method's getReturnType() method
is stored as a Class object in line 14, and that object's name is displayed in line 26.
When a method's getModifiers() method is called in line 15, an integer is returned that
represents all modifiers used with the method. The class method Modifier.toString()
takes this integer as an argument and returns the names of all modifiers associated
with it.
Search WWH ::




Custom Search