使用lambda替换Java的方法

时间:2014-03-23 04:23:13

标签: java lambda java-8

我有以下方法

private void initializeMoveOnClick(final Group window){
    window.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            //do some stuff
        }
    });
}

如何用lambda表达式替换覆盖的句柄方法声明?

2 个答案:

答案 0 :(得分:5)

您主要有两种方法:

private void initializeMoveOnClick(final Group window){
    window.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> runSomeMethod());
}

private void initializeMoveOnClick(final Group window){
    window.addEventFilter(MouseEvent.MOUSE_CLICKED, this::eventFilter);
}
private void eventFilter(MouseEvent e) {
    //do some stuff
}

答案 1 :(得分:3)

由于EventHandler是具有单个方法的接口,因此可以使用lambda表达式替换匿名类,如下所示:

private void initializeMoveOnClick(final Group window){
    window.addEventFilter(MouseEvent.MOUSE_CLICKED, (mouseEvent) -> {});
}