lambda可以访问其目标功能接口的成员吗? [英] Can a lambda access members of its target functional interface?

查看:168
本文介绍了lambda可以访问其目标功能接口的成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java8创建了一个简单的界面。因为它包含一个方法和一个默认方法。

I have created a simple interface using java8. In that it contains one method and one default method.

interface Lambda{

default void dummy(){
    System.out.println("Call this..");
}

void yummy();
}

我正在尝试使用历史方式这两种方法

I'm trying to us these two methods using the historical way like

public class DefaultCheck {

public static void main(String[] args) {

    DefaultCheck check = new DefaultCheck();
    check.activate(new Lambda() {

        @Override
        public void yummy() {
            dummy();
        }
    });

}

void activate(Lambda lambda){
    lambda.yummy();
}

}

现在我正在尝试使用lambda表达式实现同样的事情,得到像'dummy is undefined`这样的错误

Now i'm trying to implement the same thing using lambda expression, getting error like `dummy is undefined`

check.activate(() -> {
        dummy();
    });

任何人都可以建议,如何使用Lambda表达式实现这个场景?

Can any one please suggest, how to implement this scenario using Lambda expression ??

推荐答案

无法完成。

JLS 15.27.2 解决了这个问题:


与匿名类声明中出现的代码不同,
名称的含义以及出现在lambda正文中的this和super关键字,
以及引用声明的可访问性,与周围上下文中的
相同(除了lambda参数引入
新名称)。

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).


lambda表达式的主体(包括显式和隐式)的透明度 - 也就是说,它与
周围上下文中的相同 - 允许实现更灵活,并且
防止身体中不合格的名字的含义为
,取决于重载分辨率。

The transparency of this (both explicit and implicit) in the body of a lambda expression - that is, treating it the same as in the surrounding context - allows more flexibility for implementations, and prevents the meaning of unqualified names in the body from being dependent on overload resolution.

实际上,这是不寻常的lambda表达式需要
谈论自己
(要么递归调用自己,要么调用它的
其他方法
),而更常见的是想要使用将
引用到封闭类中的东西的名称,否则这些东西将被遮蔽
(this,toString())。 如果lambda表达式需要
引用自身(就好像通过这个),则应该使用方法引用或匿名
内部类。

Practically speaking, it is unusual for a lambda expression to need to talk about itself (either to call itself recursively or to invoke its other methods), while it is more common to want to use names to refer to things in the enclosing class that would otherwise be shadowed (this, toString()). If it is necessary for a lambda expression to refer to itself (as if via this), a method reference or an anonymous inner class should be used instead.

这篇关于lambda可以访问其目标功能接口的成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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