Function pointers/delegates in Java?

前端 未结 10 1481
有刺的猬
有刺的猬 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:23

    What about this one?

    HashMap map = new HashMap();
    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).

提交回复
热议问题