如何调用存储在 HashMap 中的方法?(爪哇) [英] How to call a method stored in a HashMap? (Java)
问题描述
我有一个命令列表(i、h、t 等),用户将在命令行/终端 Java 程序中输入这些命令.我想存储命令/方法对的散列:
I have a list of commands (i, h, t, etc) that the user will be entering on a command line/terminal Java program. I would like to store a hash of command/method pairs:
'h', showHelp()
't', teleport()
这样我就可以有类似的代码:
So that I can have code something like:
HashMap cmdList = new HashMap();
cmdList.put('h', showHelp());
if(!cmdList.containsKey('h'))
System.out.print("No such command.")
else
cmdList.getValue('h') // This should run showHelp().
这可能吗?如果没有,有什么简单的方法可以做到这一点?
Is this possible? If not, what is an easy way to this?
推荐答案
使用 Java 8+ 和 Lambda 表达式
使用 lambdas(在 Java 8+ 中可用),我们可以这样做:
With Java 8+ and Lambda expressions
With lambdas (available in Java 8+) we can do it as follows:
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
接口回答.
In this case I was lazy and reused the Runnable
interface, but one could just as well use the Command
-interface that I invented in the Java 7 version of the answer.
此外,还有 () 的替代方案 ->{ ... }
语法.你也可以拥有 help
和 teleport
的成员函数,并使用 YourClass::help
.YourClass::teleport
代替.
Also, there are alternatives to the () -> { ... }
syntax. You could just as well have member functions for help
and teleport
and use YourClass::help
resp. YourClass::teleport
instead.
Programming.Guide 上的一个很棒的 Lambda 备忘单.
此处的 Oracle 教程:Java 教程™–Lambda 表达式.
Oracle tutorial here: The Java Tutorials™ – Lambda Expressions.
你真正想要做的是创建一个接口,命名为Command
(或重用Runnable
),并让你的地图类型<代码>映射<字符,命令>.像这样:
What you really want to do is to create an interface, named for instance Command
(or reuse for instance Runnable
), and let your map be of the type Map<Character, Command>
. Like this:
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
类.)
Reflection "hack"
With that said, you can actually do what you're asking for (using reflection and the Method
class.)
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");
}
}
这篇关于如何调用存储在 HashMap 中的方法?(爪哇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!