1 import java.io.FileInputStream;
2 import java.io.InputStream;
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6 import java.util.ArrayList;
7 import java.util.List;
8
9 import org.junit.Test;
10
11 public class Demo {
12
13 /**
14 * 反射类的方法
15 * @throws Exception
16 *
17 */
18
19 //public void method(){
20 @Test
21 public void test1() throws Exception{
22
23 Person p = new Person();
24
25 Class clazz = Class.forName("Person");
26
27 Method method = clazz.getMethod("method", null);
28
29 method.invoke(p, null);
30
31 }
32
33 //public void method(String name,int password){
34 @Test
35 public void test2() throws Exception{
36
37 Person p = new Person();
38
39 Class clazz = Class.forName("Person");
40
41 Method method = clazz.getMethod("method", String.class,int.class);
42
43 method.invoke(p, "zero",28);
44
45 }
46
47 //public Class[] method(String name,int[] password){
48 @Test
49 public void test3() throws Exception{
50
51 Person p = new Person();
52
53 Class clazz = Class.forName("Person");
54
55 Method method = clazz.getMethod("method", String.class,int[].class);
56
57 Class[] cs = (Class[]) method.invoke(p, "one",new int[]{1,2,3});
58
59 System.out.println(cs[0]);
60 }
61
62 //public void method(InputStream in){
63 @Test
64 public void test4() throws Exception{
65
66 Person p = new Person();
67
68 Class clazz = Class.forName("Person");
69
70 Method method = clazz.getDeclaredMethod("method", InputStream.class);
71
72 method.setAccessible(true);
73
74 method.invoke(p, new FileInputStream("c:\\1.txt"));
75 }
76
77 //public static void method(int num){
78 @Test
79 public void test5() throws Exception{
80
81 Class clazz = Class.forName("Person");
82
83 Method method = clazz.getMethod("method", int.class);
84
85 method.invoke(null,29);
86 }
87
88 //调用main方法
89 @Test
90 public void test6() throws Exception{
91
92 Class clazz = Class.forName("Person");
93
94 Method method = clazz.getMethod("main", String[].class);
95
96 method.invoke(null,(Object)new String[]{"aa","bb"});
97 }
98 }