Java:基于用户输入的运行方法?

标签 java

假设我有三种方法

method1()
method2()
method3()

并且我让用户输入与他们想要运行的方法相对应的数字,有没有办法直接从他们的输入运行它?即,不要使用类似的 if 语句

System.out.println("Which method would you like to run? 1/2/3");
String input = reader.readLine();
if(input == 1){method1();}
if(input == 2){method2();}
...

等等。相反,能够拥有类似的东西

System.out.println("Which method would you like to run? 1/2/3");
String input = reader.readLine();
method(input)();

最佳答案

是的,您可以通过使用如下界面来实现这一点:

interface A {
    void run();
}

public void method1() {}

public void method2() {}

public void mainMethod(String[] args) {
    // Initialise the method map - note, you only have to do this once
    // So, this initialisation code can go into a constructor
    // And mothodMap can be declared as a final instance variable.
    A methodOne = new A() { @Override public void run() { method1(); } };
    A methodTwo = new A() { @Override public void run() { method2(); } };

    Map<Integer, A> methodMap = new HashMap<>();
    methodMap.put(1, methodOne);
    methodMap.put(2, methodTwo);

    Integer input = /* get it from user*/ 1;
    A aMethod = methodMap.get(input);
    aMethod.run();

}

关于Java:基于用户输入的运行方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489474/

相关文章:

java - 使用 jsoup 提取 href

java - 选择 ListView 项目后应用程序自动关闭

java - Jackson:我怎样才能忽略 getter 而解析 setter?

java - 无法确定返回 SortedSet 的方法的返回类型

java - 并行度为 1 的串行和并行执行之间的区别

java - 将 CookieStore 转换为字符串 : pb with encode/decode value

java - Android/Java 上的数据报传输层安全性 (DTLS)

java - Log4j:无法使用 Log4j SMTP Appenders 发送邮件

java - 当我尝试访问手机的外部存储器时应用程序崩溃

java - 实现 OAUTH 提供者 Java - 生成消费者 key 和 secret