如何创建一个将方法用作值的HashMap?

huangapple go评论87阅读模式
英文:

How to create a HashMap with methods as values?

问题

我正在编写一个能够接收多个指令的小程序。每个指令都应该调用不同的方法。我在考虑是否有一种方法可以将所有这些方法放入一个HashMap中,并通过获取与指令键配对的值来直接调用它们,而不是使用if语句,这样可以使事情变得更简单。但据我所了解,这似乎是不可能的,因为在Java中,方法不被视为对象。尽管如此,了解是否有一种方法来实现这一点仍然是有教育意义的。

英文:

I am working a small program which can receive several commands. Each of these commands should cause different methods to run. I was thinking that if there were a way to put all the methods into a HashMap and invoke them directly by getting the value paired with the command Key instead of using if statements, it could make things much simpler but as far as I understand this is not possible since methods aren't treated as objects in Java. Still, it will be educative to find out if there is a way to do this.

答案1

得分: 2

Methods 不是对象(至少大多数情况下不是),但有一个与您想要的相匹配的概念:函数式接口,它被定义为具有正好一个抽象方法的接口。两个开箱即用的候选接口是 Runnable,它不接受参数,以及 Consumer,它接受一个参数,如果您想要传入某种输入(如 Scanner),可能是最佳选择。(如果您还想要可配置的输出,带有 ScannerPrintWriterBiConsumer 可能适合。)

Java 有一个称为 方法引用 的便利功能,可以自动将方法转换为函数式接口的实例。组合在一起,可能是这样的:

Map<String, Consumer<Scanner>> commands = new HashMap<>();
...
commands.put("foo", someCommand::go); // 其中 someCommand 是一个具有 go(Scanner) 方法的变量
commands.put("bar", new OtherCommand());
commands.put("hello", unused -> { System.out.println("Hello!"); });
...
String commandName = scanner.next();
commands.get(commandName).accept(scanner);
英文:

Methods aren't objects (at least mostly not), but there is a concept that matches what you want: the functional interface, which is defined as an interface that has exactly one abstract method. Two out-of-the-box candidates are Runnable, which takes no parameters, and Consumer, which takes a single parameter and might be the best option if you want to pass in some kind of input (like a Scanner). (If you also want a configurable output, BiConsumer taking a Scanner and a PrintWriter might be suitable.)

Java has a convenience feature called method references that can automatically transform a method into an instance of a functional interface. Put together, it might look like this:

Map&lt;String, Consumer&lt;Scanner&gt;&gt; commands = new HashMap&lt;&gt;();
...
commands.put(&quot;foo&quot;, someCommand::go); // where someCommand is a variable with a go(Scanner) method
commands.put(&quot;bar&quot;, new OtherCommand());
commands.put(&quot;hello&quot;, unused -&gt; { System.out.println(&quot;Hello!&quot;); });
...
String commandName = scanner.next();
commands.get(commandName).accept(scanner);

答案2

得分: 0

这不是一个好主意,将方法作为哈希映射的值并不满足shell命令复杂的场景,也许你可以使用Runnable对象作为值。

另一个解决方案是,你可以使用Spring Shell。

@ShellMethod("commandName")
public String doSomething(String param) {
    return String.format("Hi %s", param);
}
英文:

This is not a good idea, make methods as hashmap value don't satisfied shell command complex scene, maybe you can use Runnable Object as value.

Another solution, you can use Spring Shell.

@ShellMethod(&quot;commandName&quot;)
public String doSomething(String param) {
    return String.format(&quot;Hi %s&quot;, param);
}

huangapple
  • 本文由 发表于 2020年10月13日 09:00:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64327046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定