当使用 C/C++ 或 Python 编程时,我有时会根据指定的键使用字典来引用函数。但是,我真的不知道如何在 Java 中拥有相同的——或者至少是相似的——行为,从而允许我动态键函数(或方法,在 Java 俚语中)关联。
此外,我确实找到了有人建议的 HashMap 技术,但这是最好和最优雅的方法吗?我的意思是,为我想使用的每个方法创建一个新类似乎很多。
我非常感谢对此的每一个意见。
最佳答案
您不需要为每个操作创建一个完整的名称类。您可以使用匿名内部类:
public interface Action<T>
{
void execute(T item);
}
private static Map<String, Action<Foo>> getActions()
{
Action<Foo> firstAction = new Action<Foo>() {
@Override public void execute(Foo item) {
// Insert implementation here
}
};
Action<Foo> secondAction = new Action<Foo>() {
@Override public void execute(Foo item) {
// Insert implementation here
}
};
Action<Foo> thirdAction = new Action<Foo>() {
@Override public void execute(Foo item) {
// Insert implementation here
}
};
Map<String, Action<Foo>> actions = new HashMap<String, Action<Foo>>();
actions.put("first", firstAction);
actions.put("second", secondAction);
actions.put("third", thirdAction);
return actions;
}
(然后将其存储在静态变量中。)
好吧,虽然它不如 lambda 表达式方便,但也不错。
关于java - 在 Java 中获得 "functions in a dictionary"最实用的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1145175/