假设我有三种方法
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/