JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。以下为JAVA中运用反射的实例:
1 /** 2 @version 1.1 2004-02-21 3 @author Cay Horstmann 4 */ 5 6 import java.util.*; 7 import java.lang.reflect.*; 8 9 public class ReflectionTest 10 { 11 public static void main(String[] args) 12 { 13 // read class name from command line args or user input 14 String name; 15 if (args.length > 0) 16 name = args[0]; 17 else 18 { 19 Scanner in = new Scanner(System.in); 20 System.out.println("Enter class name (e.g. java.util.Date): "); 21 name = in.next(); 22 } 23 24 try 25 { 26 // print class name and superclass name (if != Object) 27 Class cl = Class.forName(name); 28 Class supercl = cl.getSuperclass(); 29 System.out.print("class " + name); 30 if (supercl != null && supercl != Object.class) 31 System.out.print(" extends " + supercl.getName()); 32 33 System.out.print("\n{\n"); 34 printConstructors(cl); 35 System.out.println(); 36 printMethods(cl); 37 System.out.println(); 38 printFields(cl); 39 System.out.println("}"); 40 } 41 catch(ClassNotFoundException e) { e.printStackTrace(); } 42 System.exit(0); 43 } 44 45 /** 46 Prints all constructors of a class 47 @param cl a class 48 */ 49 public static void printConstructors(Class cl) 50 { 51 Constructor[] constructors = cl.getDeclaredConstructors(); 52 53 for (Constructor c : constructors) 54 { 55 String name = c.getName(); 56 System.out.print(" " + Modifier.toString(c.getModifiers())); 57 System.out.print(" " + name + "("); 58 59 // print parameter types 60 Class[] paramTypes = c.getParameterTypes(); 61 for (int j = 0; j < paramTypes.length; j++) 62 { 63 if (j > 0) System.out.print(", "); 64 System.out.print(paramTypes[j].getName()); 65 } 66 System.out.println(");"); 67 } 68 } 69 70 /** 71 Prints all methods of a class 72 @param cl a class 73 */ 74 public static void printMethods(Class cl) 75 { 76 Method[] methods = cl.getDeclaredMethods(); 77 78 for (Method m : methods) 79 { 80 Class retType = m.getReturnType(); 81 String name = m.getName(); 82 83 // print modifiers, return type and method name 84 System.out.print(" " + Modifier.toString(m.getModifiers())); 85 System.out.print(" " + retType.getName() + " " + name + "("); 86 87 // print parameter types 88 Class[] paramTypes = m.getParameterTypes(); 89 for (int j = 0; j < paramTypes.length; j++) 90 { 91 if (j > 0) System.out.print(", "); 92 System.out.print(paramTypes[j].getName()); 93 } 94 System.out.println(");"); 95 } 96 } 97 98 /** 99 Prints all fields of a class 100 @param cl a class 101 */ 102 public static void printFields(Class cl) 103 { 104 Field[] fields = cl.getDeclaredFields(); 105 106 for (Field f : fields) 107 { 108 Class type = f.getType(); 109 String name = f.getName(); 110 System.out.print(" " + Modifier.toString(f.getModifiers())); 111 System.out.println(" " + type.getName() + " " + name + ";"); 112 } 113 } 114 }