Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Reference to the final field from lambda expression

Recently I've found a subtle difference between anonymous class and lambda expression:

public class FinalTest {
    final Runnable x = new Runnable() {
        @Override
        public void run() {
            System.out.println(x.hashCode());
        }
    };

    final Runnable y = () -> System.out.println(y.hashCode()); 
}

Usually lambdas are equivalent to the anonymous classes. Even my Eclipse IDE has the refactoring to convert the x to lambda (it becomes exactly like y) and convert y to anonymous class (it becomes exactly like x). However the lambda gives me a compilation error while anonymous class can be perfectly compiled. The error message looks like this:

>javac FinalTest.java
FinalTest.java:9: error: self-reference in initializer
    final Runnable y = () -> System.out.println(y.hashCode());
                                                ^
1 error

So the question is: why there's such difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This has to do with JLS #8.3.3 dealing with forward references. In particular, if you use a fully qualified name it compiles (because the third condition of that rule becomes false The use is a simple name in either an instance variable initializer of C or an instance initializer of C):

final Runnable y = () -> System.out.println(this.y.hashCode());

In the case of the anonymous class, the fourth condition (C is the innermost class or interface enclosing the use) is not true because the enclosing class is the anonymous class itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...