I am trying to create a generic menu over an arbitrary type T
implementing a Menuable
interface:
public interface Procedure {
void invoke();
}
public class Menu<T extends Menuable> implements Menuable {
List<T> items; //The items of the menu
List<String> itemsDisplay; //A list of String specifying how to display each of the above items
Procedure procedure; //A method to be performed on the elements of items
public Menu(List<T> items, List<String> itemsDisplay) {
this.items = items;
this.itemsDisplay = itemsDisplay;
}
//Returns a String display of the menu
//Each item is numbered and displayed as specified by the list itemsDisplay
public String menuDisplay() {
String s = "";
int i;
for (i = 1; i <= this.itemsDisplay.size(); i++) {
s = s + i + "\t" + this.itemsDisplay.get(i-1) + "\n";
}
return s;
}
...
}
The menu will be printed on a terminal, and when the user chooses an item, I would like the menu to be able to perform any instance method on this item. Basically, here is what I would like to do:
public Menu(List<T> items, List<String> itemsDisplay, Procedure procedure) {
this.items = items;
this.itemsDisplay = itemsDisplay;
Here I would like to assign a method to this.procedure for later use,
but without specifying on which object to use it yet.
}
public void waitForAction() throws IOException {
//Display the menu to the user
System.out.println(this.menuDisplay());
BufferedReader inputs = new BufferedReader(new InputStreamReader(System.in));
int choice = 0;
//Read inputs until the user enters a valid choice
while(!(1 <= choice && choice <= this.items.size())) {
try {
choice = Integer.parseInt(inputs.readLine());
} catch(NumberFormatException e) {
}
}
//The item selected is at index (choice - 1) in the list this.items
Here I would like to use my method on this.items.get(choice - 1).
}
I am new to the idea of using methods as variables / arguments and I don't know how to do that. I heard about lambda expressions and method references in Java, but from what I understood, when using them you have to specify the method you want to use and its instance / parameters at the same time, which is awkward. Am I missing something ?