在Java中使用"字典中的函数"最实用的方法是什么?

Mar*_*ler 4 java methods function

使用C/C++或Python编程时,我有时会根据指定的键使用包含函数引用的字典.但是,我真的不知道如何在Java中使用相同的 - 或者至少是相似的 - 行为,从而允许我使用动态密钥功能(或Java方法中的方法)关联.

另外,我确实找到了有人建议的HashMap技术,但这是最优秀和最优雅的方式吗?我的意思是,为我想要使用的每个方法创建一个新类似乎很多.

我真的很感激每一个输入.

Jon*_*eet 10

您不需要为每个操作创建一个完整的名称类.您可以使用匿名内部类:

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;
}
Run Code Online (Sandbox Code Playgroud)

(然后将其存储在静态变量中.)

好的,所以它不像lambda表达那么方便,但它并不太糟糕.

  • 正如Java命名约定所推荐的那样,Execute应该是execute (3认同)