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