java反射机制,动态加载

Dynamic.java

 1 package demo_Test;
 2 
 3 import java.lang.reflect.Method;
 4 import java.util.Scanner;
 5 
 6 /**
 7  * @author Zhang 
 8  * 反射,动态加载类
 9  */
10 public class Dynamic {
11     public static void main(String[] args) throws Exception {
12         Scanner sc = new Scanner(System.in);
13         System.out.println("输入类名:");
14         String className = sc.nextLine();
15         // 动态加载类
16         Class cls = Class.forName(className);
17         // 动态获取全部方法信息
18         Method[] methodAry = cls.getDeclaredMethods();
19         // 迭代全部方法查找以test为开头的方法
20         for(Method method : methodAry) {
21             if(method.getName().startsWith("test")) {
22                 System.out.println(method);
23             }
24         }
25     }
26 }

Method.java

 1 package demo_Test;
 2 
 3 /**
 4  * @author Zhang
 5  *
 6  */
 7 public class Method {
 8     public void test1() {
 9 
10     }
11 
12     public void test2() {
13 
14     }
15 
16     public void test3() {
17 
18     }
19 
20     public void endtest() {
21 
22     }
23 
24 }

运行结果:

 

posted @ 2018-04-14 20:45  Amen-Z  阅读(193)  评论(0编辑  收藏  举报