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 }

 

转载于:https://www.cnblogs.com/fnlingnzb-learner/p/7240101.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值