Java equivalent of function mapping in Python

前端 未结 7 1431

In python, if I have a few functions that I would like to call based on an input, i can do this:

lookup = {\'function1\':function1, \'function2\':function2, \'fu         


        
7条回答
  •  日久生厌
    2021-02-04 15:42

    Java doesn't have first-class methods, so the command pattern is your friend...

    disclamer: code not tested!

    public interface Command 
    {
        void invoke();
    }
    
    Map commands = new HashMap();
    commands.put("function1", new Command() 
    {
        public void invoke() { System.out.println("hello world"); }
    });
    
    commands.get("function1").invoke();
    

提交回复
热议问题