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; if (args.length > 0) { name = args[0]; } else { Scanner in = new Scanner(System.in); System.out.println("Enter class name(e.g. java.util.Date):"); 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 " + name); if (supercl != null && supercl != Object.class) { System.out.print("extends " + supercl.getName()); } System.out.print("/n{/n"); printFields(cl); System.out.println(); printConstructors(cl); System.out.println(); printMethods(cl); System.out.println("}"); } catch(ClassNotFoundException e) { e.printStackTrace(); } } private static void printFields(Class cl) { Field[] fields = cl.getDeclaredFields(); for (Field f : fields) { Class type = f.getType(); String name = f.getName(); System.out.print(" "); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) { System.out.print(modifiers + " "); } System.out.println(type.getName() + " " + name + ";"); } } private static void printConstructors(Class cl) { Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor c : constructors) { String modifiers = Modifier.toString(c.getModifiers()); String name = c.getName(); System.out.print(" "); if (modifiers.length() > 0) { System.out.print(modifiers + " "); } System.out.print(name + "("); Class[] parameters = c.getParameterTypes(); for (int j = 0; j < parameters.length; j++) { if (j > 0) { System.out.print(", "); } System.out.print(parameters[j].getName()); } System.out.println(");"); } } private static void printMethods(Class cl) { Method[] methods = cl.getDeclaredMethods(); for (Method m : methods) { String name = m.getName(); String modifiers = Modifier.toString(m.getModifiers()); System.out.print(" "); if (modifiers.length() > 0) { System.out.print(modifiers + " "); } Class retype = m.getReturnType(); System.out.print(retype + " " + name + "("); Class[] parameters = m.getParameterTypes(); for (int j = 0; j < parameters.length; j++) { if (j > 0) { System.out.print(", "); } System.out.print(parameters[j].getName()); } System.out.println(");"); } } } 运行结果: run: Enter class name(e.g. java.util.Date): Employee class Employee { private java.lang.String name; private double salary; public Employee(java.lang.String, double); public double getSalary(); public void raiseSalary(double); public int compareTo(Employee); public volatile int compareTo(java.lang.Object); public class java.lang.String getName(); } 成功生成(总时间:4 秒)