有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

hash如何调用存储在HashMap中的方法?(爪哇)

我有一个用户将在命令行/终端Java程序中输入的命令列表(I、h、t等)。我想存储命令/方法对的散列:

'h', showHelp()
't', teleport()

这样我就可以编写如下代码:

HashMap cmdList = new HashMap();

cmdList.put('h', showHelp());
if(!cmdList.containsKey('h'))
    System.out.print("No such command.")
else
   cmdList.getValue('h')   // This should run showHelp().

这可能吗?如果不是,那么什么是实现这一点的简单方法


共 (2) 个答案

  1. # 1 楼答案

    虽然可以通过反射存储方法,但通常的方法是使用包装函数的匿名对象,即

      interface IFooBar {
        void callMe();
      }
    
    
     'h', new IFooBar(){ void callMe() { showHelp(); } }
     't', new IFooBar(){ void callMe() { teleport(); } }
    
     HashTable<IFooBar> myHashTable;
     ...
     myHashTable.get('h').callMe();
    
  2. # 2 楼答案

    如果您使用的是JDK 7,那么现在可以使用lambda表达式的方法,就像。网

    如果不是,最好的方法是创建函数对象:

    public interface Action { void performAction(); }
    
    Hashmap<string,Action> cmdList;
    
    if (!cmdList.containsKey('h')) {
        System.out.print("No such command.")
    } else {  
        cmdList.getValue('h').performAction();
    }