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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM