Search code examples
javadelegatesfunction-pointers

Function pointers/delegates in Java?


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. Is there a way of doing this without using a switch?


Solution

  • What about this one?

    HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
    map.put(Register.ID, new Runnable() { 
        public void run() { functionA(); }
    });
    map.put(NotifyMessage.ID, new Runnable() { 
        public void run() { functionB(); }
    });
    // ...
    map.get(id).run();
    

    (If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).