variable r might not have been initialized

2019-06-16 17:01发布

There's a very simple program:

public class A {
    public static void main(String[] p) {
        final Runnable r = new Runnable() {
            public void run() {
                System.out.println(r);
            }
        };
        r.run();
    }
}

And this gives:

$ javac A.java 
A.java:6: variable r might not have been initialized
                System.out.println(r);
                                   ^
1 error
  1. Why?
  2. How can a Runnable reference a variable pointing to it?

(In the real code, there is one more level (a listener), and referencing via this does not work)

标签: java final
7条回答
老娘就宠你
2楼-- · 2019-06-16 17:44

The working code is:

public class A {
    public static void main(String[] p) {
        class RunnableHolder { Runnable r; };
        final RunnableHolder r = new RunnableHolder();
        r.r = new Runnable() {
            public void run() {
                System.out.println(r.r);
            }
        };
        r.r.run();
    }
}

So it is possible to "unfinal" a variable using an auxiliary object.

It looks like this construct (an auxiliary object whose fields may be accessed from a Runnable) is exactly what the designers of Java tried to disallow. :)

查看更多
登录 后发表回答