码迷,mamicode.com
首页 > 编程语言 > 详细

java把函数作为参数传递

时间:2017-07-26 17:52:56      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:rgs   blog   switch   bre   lang   reflect   user   exce   system   

利用反射。在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 }

 

java把函数作为参数传递

标签:rgs   blog   switch   bre   lang   reflect   user   exce   system   

原文地址:http://www.cnblogs.com/fnlingnzb-learner/p/7240101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!