使用 Java 8+ 和 Lambda 表达式
使用 lambdas(在 Java 8+ 中可用)我们可以这样做:
class Test {
public static void main(String[] args) throws Exception {
Map<Character, Runnable> commands = new HashMap<>();
// Populate commands map
commands.put('h', () -> System.out.println("Help"));
commands.put('t', () -> System.out.println("Teleport"));
// Invoke some command
char cmd = 't';
commands.get(cmd).run(); // Prints "Teleport"
}
}
在这种情况下,我很懒惰并重用了Runnable 接口,但也可以使用我在Java 7 版本的答案中发明的Command-接口。
此外,() -> { ... } 语法还有其他替代方法。您也可以拥有help 和teleport 的成员函数,并分别使用YourClass::help。 YourClass::teleport 代替。
Java 7 及以下
您真正想要做的是创建一个接口,例如命名为Command(或重复使用例如Runnable),并让您的映射为Map<Character, Command> 类型。像这样:
import java.util.*;
interface Command {
void runCommand();
}
public class Test {
public static void main(String[] args) throws Exception {
Map<Character, Command> methodMap = new HashMap<Character, Command>();
methodMap.put('h', new Command() {
public void runCommand() { System.out.println("help"); };
});
methodMap.put('t', new Command() {
public void runCommand() { System.out.println("teleport"); };
});
char cmd = 'h';
methodMap.get(cmd).runCommand(); // prints "Help"
cmd = 't';
methodMap.get(cmd).runCommand(); // prints "teleport"
}
}
反射“黑客”
话虽如此,您可以实际上做您要求的事情(使用反射和Method 类。)
import java.lang.reflect.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
Map<Character, Method> methodMap = new HashMap<Character, Method>();
methodMap.put('h', Test.class.getMethod("showHelp"));
methodMap.put('t', Test.class.getMethod("teleport"));
char cmd = 'h';
methodMap.get(cmd).invoke(null); // prints "Help"
cmd = 't';
methodMap.get(cmd).invoke(null); // prints "teleport"
}
public static void showHelp() {
System.out.println("Help");
}
public static void teleport() {
System.out.println("teleport");
}
}