Function pointers/delegates in Java?

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

    Have you ever used Swing/AWT? Their Event hierarchy solves a similar problem. The way Java passes functions around is with an interface, for example

    public interface ActionHandler {
        public void actionPerformed(ActionArgs e);
    }
    

    Then, if you want to map integers onto these objects, you could use something like a java.util.HashMap to manage that. The actual implementations can either go in anonymous classes (Java's best approximation of "lambda") or in proper classes somewhere. Here's the anonymous class way:

    HashMap handlers;
    handlers.put(ACTION_FROB, new ActionHandler() {
        public void actionPerformed(ActionArgs e) {
            // Do stuff
            // Note that any outer variables you intend to close over must be final.
        }
    });
    handlers.get(ACTION_FROB).actionPerformed(foo);
    

    (edit) If you want to be even more abusive, you can initialize the HashMap like so:

    HashMap m = new HashMap() {{
        put(0,"hello");
        put(1,"world");
    }};
    

提交回复
热议问题