Java Reference
In-Depth Information
of Constructor objects. Even though Class is in the package java.lang , the Construct-
or , Method , and Field objects it returns are in java.lang.reflect , so you need an import
of this package. The ListMethods class (see Example 23-1 ) shows how get a list of methods
in a class whose name is known at runtime.
Example 23-1. ListMethods.java
public
public class
class ListMethods
ListMethods {
public
public static
static void
void main ( String [] argv ) throws
throws ClassNotFoundException {
iif ( argv . length == 0 ) {
System . err . println ( "Usage: ListMethods className" );
return
return ;
}
Class <?> c = Class . forName ( argv [ 0 ]);
Constructor <?>[] cons = c . getConstructors ();
printList ( "Constructors" , cons );
Method [] meths = c . getMethods ();
printList ( "Methods" , meths );
}
static
static void
void printList ( String s , Object [] o ) {
System . out . println ( "*** " + s + " ***" );
for
for ( int
int i = 0 ; i < o . length ; i ++)
System . out . println ( o [ i ]. toString ());
}
}
For example, you could run Example 23-1 on a class like java.lang.String and get a fairly
lengthy list of methods; I'll only show part of the output so you can see what it looks like:
> java reflection.ListMethods java.lang.String
*** Constructors ***
public java.lang.String( )
public java.lang.String(java.lang.String)
public java.lang.String(java.lang.StringBuffer)
public java.lang.String(byte[])
// and many more...
*** Methods ***
public static java.lang.String java.lang.String.copyValueOf(char[])
public static java.lang.String java.lang.String.copyValueOf(char[],int,int)
public static java.lang.String java.lang.String.valueOf(char)
// and more valueOf( ) forms...
public boolean java.lang.String.equals(java.lang.Object)
public final native java.lang.Class java.lang.Object.getClass( )
// and more java.lang.Object methods...
Search WWH ::




Custom Search