java - 如何将方法分配为属性以便以后在任何兼容的对象上使用它?
问题描述
我正在尝试在T
实现Menuable
接口的任意类型上创建通用菜单:
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;
}
...
}
菜单将打印在终端上,当用户选择一个项目时,我希望菜单能够对该项目执行任何实例方法。基本上,这是我想做的:
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).
}
我对使用方法作为变量/参数的想法很陌生,但我不知道该怎么做。我听说过 Java 中的 lambda 表达式和方法引用,但据我了解,在使用它们时,您必须同时指定要使用的方法及其实例/参数,这很尴尬。我错过了什么吗?