How can a Java lambda-expression reference itself?

后端 未结 3 1892
悲哀的现实
悲哀的现实 2021-02-04 16:27

I found this article to be very informative in comparison of old-style functions to new Java-8 lambda-functions and parallel processing. One thing I couldn\'t quite understand w

3条回答
  •  后悔当初
    2021-02-04 16:45

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

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

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

提交回复
热议问题