動的呼び出しクラスを反射する静的メソッドとインスタンスメソッド
1 mport java.lang.reflect.Constructor;
2 import java.lang.reflect.Method;
3
4
5 public class CallMethod {
6
7 public static void main(String[] args) throws Exception {
8 // TestClass Class
9 Class testClass = Class.forName(TestClass.class.getName());
10
11
12 // (1) Class newInstance ,
13 TestClass objectA = (TestClass) testClass.newInstance();
14 System.out.println("Class newInstance() TestClass : "
15 + objectA.toString());
16 // (2) 。
17 Constructor[] cons = testClass.getDeclaredConstructors();
18 System.out.println("testClass " + cons.length + " ");
19 Constructor con = null;
20 for (int i = 0; i < cons.length; i++) {
21 con = cons[i];
22 //
23 if (con.getParameterTypes().length == 0) {
24 // Constructor newInstance
25 objectA = (TestClass) con.newInstance(null);
26 System.out
27 .println("Constructor newInstance() TestClass : "
28 + objectA.toString());
29 } else {
30 //
31 objectA = (TestClass) con.newInstance(new Object[] {
32 new Integer(55), new Integer(88) });
33 System.out
34 .println("Constructor newInstance() TestClass : "
35 + objectA.toString());
36 }
37 }
38
39
40 //
41 Method[] methods = testClass.getMethods();
42 //
43 Method saddMethod1 = testClass.getMethod("sadd", null);
44 Method addMethod1 = testClass.getMethod("add", null);
45 //
46 Method saddMethod2 = testClass.getMethod("sadd", new Class[] {
47 int.class, int.class });
48 Method addMethod2 = testClass.getMethod("add", new Class[] { int.class,
49 int.class });
50
51
52 //
53 int result = ((Integer) saddMethod1.invoke(null, null)).intValue();
54 System.out.println(" sadd: " + result);
55 //
56 result = ((Integer) saddMethod2.invoke(null, new Object[] {
57 new Integer(30), new Integer(70) })).intValue();
58 System.out.println(" 30, 70 sadd: " + result);
59
60
61 objectA = (TestClass) testClass.newInstance();
62 //
63 result = ((Integer) addMethod1.invoke(objectA, null)).intValue();
64 System.out.println(" add: " + result);
65 //
66 result = ((Integer) addMethod2.invoke(objectA, new Object[] {
67 new Integer(130), new Integer(170) })).intValue();
68 System.out.println(" 130, 170 add: " + result);
69
70 //
71 // Method sub = testClass.getMethod("sub", null);
72 // System.out.println(sub.invoke(objectA, null));
73 }
74
75 //
76 class TestClass {
77 //
78 static int sa = 100;
79 static int sb = 50;
80 //
81 int a;
82 int b;
83 //
84 public TestClass() {
85 this.a = 5;
86 this.b = 10;
87 }
88 //
89 public TestClass(int a, int b) {
90 this.a = a;
91 this.b = b;
92 }
93
94 // , add
95 public static int sadd() {
96 return sa + sb;
97 }
98 public static int sadd(int a, int b) {
99 return a + b;
100 }
101 // , add
102 public int add() {
103 return this.a + this.b;
104 }
105 public int add(int a, int b) {
106 return a + b;
107 }
108 public String toString() {
109 return "a = " + this.a + "; b = " + this.b;
110 }
111 //
112 private int sub() {
113 return this.a - this.b;
114 }
115 }
116 }
転載先:https://www.cnblogs.com/wslcs/p/5045734.html