使用Java 8+和Lambda表达式
使用Lambda表达式(在Java 8+中可用),我们可以按以下方式完成:
class Test {
public static void main(String[] args) throws Exception {
Map<Character, Runnable> commands = new HashMap<>();
commands.put('h', () -> System.out.println("Help"));
commands.put('t', () -> System.out.println("Teleport"));
char cmd = 't';
commands.get(cmd).run();
}
}
在这种情况下,我有点懒,重用了
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();
cmd = 't';
methodMap.get(cmd).runCommand();
}
}
反射“黑科技”
话虽如此,您确实可以使用反射和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);
cmd = 't';
methodMap.get(cmd).invoke(null);
}
public static void showHelp() {
System.out.println("Help");
}
public static void teleport() {
System.out.println("teleport");
}
}