package v1ch02;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;
public class ReflectionTest {
public static void main(String[] args) {
String name = null;
if (args.length > 0) {
name = args[0];
} else {
Scanner in = new Scanner(System.in);
name = in.next();
}
try {
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.print("class" + " " + cl.getName() + " ");
if (supercl != null && supercl != Object.class)
System.out.print("extends" + supercl.getName());
System.out.print("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void printFields(Class cl) {
Field[] fields = cl.getFields();
for(Field f : fields){
System.out.print(" ");
String modifiers = Modifier.toString(f.getModifiers());
if(modifiers.length() > 0)System.out.print(modifiers+" ");
Class retType = f.getType();
System.out.println(retType.getName()+" "+f.getName()+";");
}
}
private static void printMethods(Class cl) {
Method[] methods = cl.getMethods();
for (Method m : methods) {
System.out.print(" ");
String modifiers = Modifier.toString(m.getModifiers());
if(modifiers.length() > 0)System.out.print(modifiers+" ");
Class retType = m.getReturnType();
System.out.print(retType.getName()+" ");
System.out.print(m.getName()+"(");
Class[] paramtersType = m.getParameterTypes();
for(int i = 0;i<paramtersType.length;i++){
if(i>0)System.out.print(",");
System.out.print(paramtersType[i].getName());
}
System.out.println(");");
}
}
private static void printConstructors(Class cl) {
Constructor[] constructors = cl.getConstructors();
for (Constructor c : constructors) {
System.out.print(" ");
String modifiers = Modifier.toString(c.getModifiers());
if (modifiers.length() > 0)
System.out.print(modifiers + " ");
System.out.print(c.getName());
Class[] parametersType = c.getParameterTypes();
for (int i = 0; i < parametersType.length; i++) {
if (i > 0)
System.out.print(",");
System.out.print(parametersType[i].getName());
}
System.out.println(");");
}
}
}