Function pointers/delegates in Java?

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

    You could interface static methods. This method allows you to specify parameters too. Declare your interface...

    public interface RouteHandler {
        void handleRequest(HttpExchange t) throws IOException;
    }
    

    And your map...

    private Map routes = new HashMap<>();
    

    Then implement static methods that match the interface/params...

    public static void notFound(HttpExchange t) throws IOException {
        String response = "Not Found";
    
        t.sendResponseHeaders(404, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
    

    You can then add those methods into your map...

    routes.put("/foo", CoreRoutes::notFound);
    

    and call them as follows...

    RouteHandler handler = routes.get("/foo");
    handler.handleRequest(exchange);
    

提交回复
热议问题