java把函數作為參數傳遞

來源:互聯網
上載者:User

標籤: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 User45 {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把函數作為參數傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.