lambda - Java lambda 表达式如何引用自身?

标签 lambda java-8

我找到了this article在旧式函数与新 Java-8 lambda 函数和并行处理的比较中提供了非常丰富的信息。我不太明白的一件事是对 lambda 函数的一项限制:来自第 4 页:

3.3 Preconditions Although lambda expressions are intended as a more con- cise alternative to AIC , they are not a complete replacement. There are several preconditions that LambdaFicator checks before refactoring an AIC into a lambda expression. These preconditions are inherent to how lambda expressions are implemented in Java, not limitations of our tool. (P1) AIC must instantiate from an interface. Instances of abstract or concrete classes cannot be converted to lambda expressions. (P2) AIC must have no fields, and declare only one method. A lambda expression represents a single anonymous func- tion; therefore, an AIC with multiple methods can not be converted to a single lambda expression. (P3) AIC must not have references to this or super . In a lambda expression, this and super are lexically scoped, meaning they are interpreted just as they would be in the enclosing environment, e.g., as if they appeared in the state- ment before the lambda expression [6]. However, in an AIC they refer to the inner class itself. (P4) AIC must not declare a recursive method. In order to perform the recursive call, we must obtain a reference to the anonymous function. While LambdaFicator could perform this refactoring, this could introduce unneeded complexity into the code and harm understandability.

在 P4 上,“AIC 不得声明递归方法...LambdaFicator 可以执行此重构...”,如何重构 lambda 表达式以引用自身?因为根据定义,这些 lambda 匿名函数没有可以引用的名称,并且没有对自身的引用(上面的 P3)。?

最佳答案

public class Test {
    static Runnable r;

    public static void main(String... args) {
        r = () -> r.run();
        r.run();
    }
}

Runnable 在运行时从字段 r 获取对其自身的引用。

如果您不喜欢添加字段,也可以使用长度为 1 的数组来存储引用。

关于lambda - Java lambda 表达式如何引用自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27762488/

相关文章:

java - 用 Java-8 Streams 替换 'for' 循环中的 if-else

python - 旋转 Pandas 表 - 特殊问题

java - Lambda 将 List 转换为共享值映射到唯一值列表

c# - 使用带有 lambda 表达式的 db 获取数据并合并

java - 如何在 Java 8 中执行这个并行任务

java - 指数 b 中的最后一位数字

java - 如何在Java中使用JacksonJSONProvider ObjectMapper()类?

java - 如何使用 Java 流将子生成的列表组合成单个列表?

c# - 如何删除 lambda 事件处理程序

java-8 - 方法引用不履行功能接口(interface)契约,但可以编译。怎么可能?