Any way to map method calls?
I was wondering whether it was possible to have method calls as the value in a HashMap (or LinkedHashMap). For example, I'm designing a virtual PDA program for a uni assignment. One of my classes is a 'Menu' class which acts as sort of a template for the PDA class's menus. What I'm aiming for is a HashMap in the Menu class, where the key is the menu option (type String) and the value is the method called by selecting that option. The PDA class will then create a bunch of Menus, and fill each Menu's map with the Menu options and the methods called by those options.
Basically I think I want a field like this in the Menu class:
private HashMap<String, [Method Call]> menuOptions
And then have a method in the PDA class that does something like this:
menuOptions.put("Option A", doSomething());
where 'Option A' is the name of the option, and 'doSomething()' is a method signature.
Thanks in advance to anyone who can help me.
Re: Any way to map method calls?
Well you could rather just have an interface like for instance called MenuOption with a method on it.
Code :
public interface MenuOption {
public void execute();
}
Then you would create your menuoptions to implement this interface and then store the reference to that object in the map.
Code :
public class MyMenuOption implements MenuOption {
public void execute() {
System.out.println('Execute in MyMenuOption was invoked');
}
}
Code :
Map<String, MenuOption> menuOptions = new HashMap<String, MenuOption>();
MyMenuOption myMenuOption = new MyMenuOption();
menuOptions.put("Option A", myMenuOption);
And then in the menu whenever someone clicks a menu item.
Code :
MenuOption clickedMenuOption = menuOptions.get(keyOfMenuOption);
clickedMenuOption.execute();
Something like that might do.
// Json