我以前问过这个问题,但我没有得到适当的答案。
如果非最终字段的值可以更改,如何在匿名类中使用它们?
class Foo{
private int i;
void bar(){
i = 10
Runnable runnable = new Runnable (){
public void run (){
System.out.println(i); //works fine
}//end method run
}//end Runnable
}//end method bar
}//end class Foo
如果在匿名类中使用的局部变量必须final
使编译器能够在匿名类代码中内联它们的值,如下所示:
前:
public class Access1 {
public void f() {
final int i = 3;
Runnable runnable = new Runnable() {
public void run() {
System.out.println(i);
}//end method run
};//end anonymous class
}//end method f
}//end class Access1
后:
public class Access1 {
public Access1() {}//end constructor
public void f() {
Access1$1 access1$1 = new Access1$1(this);
}//end method f
}//end class Access1
和
class Access1$1 implements Runnable {
Access1$1(Access1 access1) {
this$0 = access1;
}//end constructor
public void run() {
System.out.println(3);
}//end method run
private final Access1 this$0;
}//end class Access1$1
那么编译器如何内联非最终字段的值呢?