且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-05 14:39:58

public class Test {
    static Runnable r;

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

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

The Runnable obtains a reference to itself from the field r when it is run.

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

You could also use a length 1 array to store the reference if you don't like adding a field.