反射机制:反射机制就是程序在运行时动态加载一个类来进行,动态new一个对象出来,然后动态地去了解这个对象的内部结构,动态地去调用这个对象的某些方法。

1 import java.lang.reflect.InvocationTargetException;
2 import java.lang.reflect.Method;
3
4
5
6 public class TestReflection {
7
8
9 public static void main(String[] args) {
10
11 //String str = "com.mysql.jdbc.Driver";
12 String str = "TTT";
13 Class c = null;
14 try {
15 c = Class.forName(str);
16 Object o=c.newInstance();
17 Method [] methods=c.getMethods();//Ctrl+Shift+M(先把光标放在需导入包的类名上) 作用是加Import语句。
18 for(Method m:methods){
19 //System.out.println(m.getName());
20 if(m.getName()=="mm"){
21 m.invoke(o,1);
22 }
23 }
24 } catch (ClassNotFoundException e) {
25
26 e.printStackTrace();
27 } catch (InstantiationException e) {
28
29 e.printStackTrace();
30 } catch (IllegalAccessException e) {
31
32 e.printStackTrace();
33 }
34 catch(InvocationTargetException e){
35 e.printStackTrace();
36 }
37
38 }
39
40 }
41
42 class TTT {
43
44 static {
45 System.out.println("T loaded!");
46 }
47
48 public TTT() {
49 System.out.println("T constructed!");
50 }
51 public void mm(int i){
52 System.out.println("mm invoked!") ;
53 }
54
55 int i;
56 String s;
57
58 public void m1(int i) {
59 this.i = i;
60 }
61
62 public String getS() {
63 return this.s;
64 }
65 }
运行结果如下:
T loaded!
T constructed!
mm invoked!