java把函数作为参数传递

时间:2023-03-08 23:23:41
java把函数作为参数传递
    public class Tool {
        public void a()// /方法a
        {
            System.out.print("tool.a()...");
        }
        public void b()// 方法b
        {
            System.out.print("tool.b()...");
        }
    }

    public class Control {
        public void invoke(int flag) {
            User user = new User();
            try {
                switch (flag) {
                case 0:
                    user.use(Tool.class.getMethod("a", null));
                    break;
                default:
                    user.use(Tool.class.getMethod("b", null));
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public class User {
        public void use(Method method) {
            Tool tool = new Tool();
            try {
                method.invoke(tool, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            Control control = new Control();
            control.invoke(0);
        }
    }