1 package reflection; 2 3 import java.lang.reflect.*; 4 import java.util.*; 5 6 public class ReflectionTest { 7 public static void main(String[] args) 8 { 9 String name; 10 if(args.length>0) name =args[0]; 11 else 12 { 13 Scanner in = new Scanner(System.in); 14 System.out.println("Enter class name (e.g. java.util.Date):"); 15 name = in.next(); 16 } 17 try 18 { 19 Class cl = Class.forName(name); 20 Class supercl = cl.getSuperclass(); 21 String modifiers = Modifier.toString(cl.getModifiers()); 22 if (modifiers.length() > 0) System.out.print(modifiers + " "); 23 System.out.print("class " + name); 24 if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName()); 25 26 System.out.print(" { "); 27 printConstructors(cl); 28 System.out.println(); 29 printMethods(cl); 30 System.out.println(); 31 printFields(cl); 32 System.out.println("}"); 33 34 } 35 catch (ClassNotFoundException e) 36 { 37 e.printStackTrace(); 38 } 39 System.exit(0); 40 } 41 public static void printConstructors(Class cl) 42 { 43 Constructor[] constructors = cl.getDeclaredConstructors(); 44 for(Constructor c:constructors) 45 { 46 String name = c.getName(); 47 System.out.print(" "); 48 String modifiers = Modifier.toString(c.getModifiers()); 49 if(modifiers.length()>0) System.out.print(modifiers+" "); 50 System.out.print(name+"("); 51 52 Class[] paramTypes = c.getParameterTypes(); 53 for (int j=0; j<paramTypes.length; j++) 54 { 55 if(j>0) System.out.print(", "); 56 System.out.print(paramTypes[j].getName()); 57 } 58 System.out.println(");"); 59 } 60 } 61 62 public static void printMethods(Class cl) 63 { 64 Method[] methods = cl.getDeclaredMethods(); 65 66 for(Method m:methods) 67 { 68 Class retType = m.getReturnType(); 69 String name = m.getName(); 70 71 System.out.print(" "); 72 String modifiers = Modifier.toString(m.getModifiers()); 73 if(modifiers.length()>0) System.out.print(modifiers+" ");//private static final都是修饰符 74 System.out.print(retType.getName()+" "+name + "("); 75 76 Class[] paramTypes = m.getParameterTypes();//获取一个方法的所有参数 77 for(int j=0;j<paramTypes.length;j++) 78 { 79 if(j>0) System.out.print(", "); 80 System.out.print(paramTypes[j].getName());//获取一个参数的类型 81 } 82 System.out.println(");"); 83 } 84 } 85 86 public static void printFields(Class cl) 87 { 88 Field[] fields = cl.getDeclaredFields(); 89 90 for(Field f:fields) 91 { 92 Class type = f.getType(); 93 String name = f.getName(); 94 System.out.print(" "); 95 String modifiers = Modifier.toString(f.getModifiers()); 96 if(modifiers.length()>0) System.out.print(modifiers+" "); 97 System.out.println(type.getName()+" "+ name +";"); 98 99 } 100 } 101 102 }