Once a list of the Method objects has been obtained, it's simply a matter of displaying the information on parameter types, exception types, and the return type for each method. Each of these types, whether they are fundamental or class types, is in turn represented by a Class descriptor.
The output of the program is:
name = f1
decl class = class org.duke.java.reflect.Method1
param #0 class java.lang.Object
param #1 int
exc #0 class java.lang.NullPointerException
return type = int
-----
name = main
decl class = class org.duke.java.reflect.Method1
param #0 class [Ljava.lang.String;
return type = void
-----
Obtaining Information About Constructors
A similar approach is used to find out about the constructors of a class. For example:
package org.duke.java.reflect;
import java.lang.reflect.Constructor;
public class Constructor1 {
public Constructor1() {
}
protected Constructor1(int i, double d) {
}
public static void main(String args[]) {
try {
Class cls = Class.forName("org.duke.java.reflect.Constructor1");
Constructor ctorlist[] = cls.getDeclaredConstructors();
for (int i = 0; i < ctorlist.length; i++) {
Constructor ct = ctorlist[i];
System.out.println("name = " + ct.getName());
System.out.println("decl class = " + ct.getDeclaringClass());
Class pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = ct.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}
There is no return-type information retrieved in this example, because constructors don't really have a true return type.
When this program is run, the output is:
name = org.duke.java.reflect.Constructor1
decl class = class org.duke.java.reflect.Constructor1
-----
name = org.duke.java.reflect.Constructor1
decl class = class org.duke.java.reflect.Constructor1
param #0 int
param #1 double
-----
Finding Out About Class Fields
It's also possible to find out which data fields are defined in a class. To do this, the following code can be used:
package org.duke.java.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Field1 {
private double d;
public static final int i = 37;
String s = "testing";
public static void main(String args[]) {
try {
Class cls = Class.forName("org.duke.java.reflect.Field1");
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("-----");
}