Lambda Java函数接口:如何用andThen或类似的方式包装函数
我有一些重复的代码:Lambda Java函数接口:如何用andThen或类似的方式包装函数,lambda,java-8,functional-interface,compose,Lambda,Java 8,Functional Interface,Compose,我有一些重复的代码: router.post("/fleets/:fleetid/vehicles/:boxid/ping").handler(ctx -> pingBox(pingBoxTimer, oemUrl, ctx)); router.post("/fleets/:fleetid/vehicles/:boxid/wakeup").handler(ctx -> wakeUp(wakeupTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/ping").handler(ctx -> pingBox(pingBoxTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/wakeup").handler(ctx -> wakeUp(wakeupTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/passthrough").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/expert").handler(ctx -> passthrough(passthroughTimer, oemUrl, ctx));
router.post("/fleets/:fleetid/vehicles/:boxid/door").handler(ctx -> door(doorTimer, oemUrl, ctx));
在这些方法的处理程序中,我:
- 启动计时器
- 做点什么
- 停止计时
private void handleWithTimer(Timer timer, String url, RoutingContext ctx, BiConsumer<String, RoutingContext> handler){
log.debug("saving timer");
Timer.Context timerCtx = timer.time();
ctx.put("timer", timerCtx);
handler.accept(url, ctx);
timerCtx.stop();
}
必须有一种更简洁的方式。有什么想法吗
谢谢您可以使包装功能更具可读性,如下所示:
.handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, this::pingBox));
(当然,只有在调整了pingBox的输入参数之后,您才可以这样做,看起来您已经这样做了)
.. .handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, (s, c) -> pingBox(oemUrl, ctx)));
.handler(ctx -> handleWithTimer(pingBoxTimer, oemUrl, ctx, this::pingBox));