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?
If you are using JDK 7 you can now use methods by lambda expression just like .net.
If Not the best way is to make a Function Object:
Though you could store methods through reflection, the usual way to do it is to use anonymous objects that wrap the function, i.e.
With Java 8+ and Lambda expressions
With lambdas (available in Java 8+) we can do it as follows:
In this case I was lazy and reused the
Runnable
interface, but one could just as well use theCommand
-interface that I invented in the Java 7 version of the answer.Also, there are alternatives to the
() -> { ... }
syntax. You could just as well have member functions forhelp
andteleport
and useYourClass::help
resp.YourClass::teleport
instead.A great Lambda cheat sheet over at Programming.Guide.
Oracle tutorial here: The Java Tutorials™ – Lambda Expressions.
Java 7 and below
What you really want to do is to create an interface, named for instance
Command
(or reuse for instanceRunnable
), and let your map be of the typeMap<Character, Command>
. Like this:Reflection "hack"
With that said, you can actually do what you're asking for (using reflection and the
Method
class.)