java把函数作为参数传递

利用反射。在use里面通过
method.invoke(tool, null);可以调用Tool里面的方法

 1 public class Tool {
 2      
 3     public void a()// /方法a
 4     {
 5         System.out.print("tool.a()...");
 6     }
 7  
 8     public void b()// 方法b
 9     {
10         System.out.print("tool.b()...");
11     }
12 }
13  
14  
15  
16  
17 public class Control {
18     public void invoke(int flag) {
19         User user = new User();
20         try {
21             switch (flag) {
22             case 0:
23                 user.use(Tool.class.getMethod("a", null));
24                 break;
25             default:
26                 user.use(Tool.class.getMethod("b", null));
27                 break;
28             }
29         } catch (Exception e) {
30             e.printStackTrace();
31         }
32  
33     }
34 }
35  
36  
37  
38  
39  
40  
41  
42 import java.lang.reflect.Method;
43  
44 public class User
45 {
46     public void use(Method method)
47     {
48         Tool tool = new Tool();
49         try {
50             <span style="color: #FF0000;">method.invoke(tool, null);</span>
51         } catch (Exception e) {
52             e.printStackTrace();
53         }
54     }
55  
56     public static void main(String[] args){
57         Control control = new Control();
58         control.invoke(0);
59     }
60 }

 

posted @ 2017-07-26 15:50  Boblim  阅读(36877)  评论(0编辑  收藏  举报