Function pointers/delegates in Java?

前端 未结 10 1453
有刺的猬
有刺的猬 2020-12-15 21:06

For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function.

10条回答
  •  庸人自扰
    2020-12-15 21:30

    You can use things in java.util.function (For Java 8+) to store a function. java.util.function docs

    You have to go through this list and pick an appropriate function-class to use. I'll be using BiConsumer, which says:

    Takes two inputs. Returns no result. Operates through side effects.

    import java.util.function.BiConsumer;
    import java.util.HashMap;
    import java.util.Map;
    
    public void init(){
      //>
      Map> actionMap = new HashMap<>();
      actionMap.put(123, this::someMethod);
    
      //note (optional): check key first: map.containsKey(someActionId)
      //call someMethod("argument1", "argument2")
      actionMap.get(123).accept("argument1", "argument2");
    }
    
    public void someMethod(String a, String b){
      //do something here
    }
    

提交回复
热议问题