Java 语言 lambda 表达式中的 this

Java 8 中首次引入了 lambda 表达式,在 Java 8 语言规范《The Java Language Specification Java SE 8 Edition》中,第 15.27.2 节“Lambda Body”中有如下表述:

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).

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.

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 主体中的名称、 thissuper 关键字的含义,以及引用声明的可访问性,与周围上下文中的一致(除了 lambda 参数引入的新名称)。

lambda 表达式主体中的 this (显示和隐式)的透明性(也就是说,将其视为与周围上下文一致),为实现提供了更大的灵活性,并防止主体中非限定名称的含义依赖于重载解析。

实际上,lambda 表达式需要谈论自身的情况并不常见(无论是递归调用自身,还是调用它的其他方法),而更常见的情况是,希望使用名称来引用封闭类中的内容,否则会被遮蔽(this, toString())。如果 lambda 表达式需要引用自身(就像通过 this),则应使用方法引用或匿名内部类。

也就是说,lambda 表达式中的 this,并不指向自己,而是指向外面一层的类。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容