以前にこの質問をしましたが、適切な回答が得られませんでした。
値が変わる可能性がある場合、非最終フィールドを匿名クラス クラスでどのように使用できますか?
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
それでは、コンパイラはどのようにして非 final フィールドの値をインライン化できるのでしょうか?