12/14/09

Java - display all methods in a class

This method can display all metjods inside a class. This will use the Class class, which is part of java.lang package, is used to learn about and create classes,interfaces,and primitive types. To try the below program, enter:
java SeeMethods java.util.Random, and you will get

Method: next()
Modifiers: protected synchronized
Return type: int
Parameters: int

Method: nextDouble()
Modifiers: public
Return type: double
Parameters:
......

--------------------------------
import java.lang.reflect.*;


public class SeeMethods {
public static void main(String[] arguments) {
Class inspect;
try {
if (arguments.length > 0)
inspect = Class.forName(arguments[0]);
else
inspect = Class.forName("SeeMethods");
Method[] methods = inspect.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method methVal = methods[i];
Class returnVal = methVal.getReturnType();
int mods = methVal.getModifiers();
String modVal = Modifier.toString(mods);
Class[] paramVal = methVal.getParameterTypes();
StringBuffer params = new StringBuffer();
for (int j = 0; j < paramVal.length; j++) {
if (j > 0)
params.append(", ");
params.append(paramVal[j].getName());
}
System.out.println("Method: " + methVal.getName() + "()");
System.out.println("Modifiers: " + modVal);
System.out.println("Return Type: " + returnVal.getName());
System.out.println("Parameters: " + params + "\n");
}
} catch (ClassNotFoundException c) {
System.out.println(c.toString());
}
}
}