Reputation: 77
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.
Upvotes: 0
Views: 853
Reputation: 1
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("commandName")
public String doSomething(String param) {
return String.format("Hi %s", param);
}
Upvotes: 0
Reputation: 77196
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<String, Consumer<Scanner>> commands = new HashMap<>();
...
commands.put("foo", someCommand::go); // where someCommand is a variable with a go(Scanner) method
commands.put("bar", new OtherCommand());
commands.put("hello", unused -> { System.out.println("Hello!"); });
...
String commandName = scanner.next();
commands.get(commandName).accept(scanner);
Upvotes: 2