Java 8 Lambda 表达式 - 嵌套类中的多个方法怎么样 [英] Java 8 Lambda Expressions - what about multiple methods in nested class

查看:23
本文介绍了Java 8 Lambda 表达式 - 嵌套类中的多个方法怎么样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关新功能的信息:http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html

I'm reading about the new features at: http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html

我看到了下面的例子:

使用匿名类:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        System.out.println("Action Detected");
    }
});

使用 Lambda:

button.addActionListener(e -> {
    System.out.println("Action Detected");
});

如果有人想在匿名类中实现多个方法,他们会用 MouseListener 做什么,例如:

What would someone do with a MouseListener if they wanted to implement multiple methods within the anonymous class, e.g.:

public void mousePressed(MouseEvent e) {
    saySomething("Mouse pressed; # of clicks: "
               + e.getClickCount(), e);
}

public void mouseReleased(MouseEvent e) {
    saySomething("Mouse released; # of clicks: "
               + e.getClickCount(), e);
}

...等等?

推荐答案

您可以通过使用辅助接口将多方法接口与 lambda 配合使用.这适用于此类侦听器接口,其中不需要的方法的实现是微不足道的(即我们也可以执行 MouseAdapter 提供的内容):

You can use multi-method interfaces with lambdas by using helper interfaces. This works with such listener interfaces where the implementations of unwanted methods are trivial (i.e. we can just do what MouseAdapter offers too):

// note the absence of mouseClicked…
interface ClickedListener extends MouseListener
{
    @Override
    public default void mouseEntered(MouseEvent e) {}

    @Override
    public default void mouseExited(MouseEvent e) {}

    @Override
    public default void mousePressed(MouseEvent e) {}

    @Override
    public default void mouseReleased(MouseEvent e) {}
}

你只需要定义一次这样的辅助接口.

You need to define such a helper interface only once.

现在你可以为 Component c 上的点击事件添加一个监听器,如下所示:

Now you can add a listener for click-events on a Component c like this:

c.addMouseListener((ClickedListener)(e)->System.out.println("Clicked !"));

这篇关于Java 8 Lambda 表达式 - 嵌套类中的多个方法怎么样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆