To access the field x of an outer class A from an inner class B, I realize that you can use "A.this.x". But what if the outer class is also anonymous? For example,
public class Main1 {
public static void main(String[] args) {
Comparable c1 = new Comparable(){
int x = 3;
public int compareTo(Object o) {
Comparable c2 = new Comparable(){
int x = 4;
public int compareTo(Object o) {
return x; // <-- THIS LINE
}
};
return c2.compareTo(o);
}
};
System.out.println(c1.compareTo(null));
}
}
When this code is run, the value of 4 is printed because that is the value of c2's field x. However, I would like to change the line marked "THIS LINE" so that it returns the outer class's x (that is, c1's field x, with the value 3). If the outer class (that is, c1's class) were a named class A, then I could replace
return x;
with
return A.this.x;
But since the outer class is also anonymous, I don't have a name to use.
Question: Is there a way to modify the line labeled "THIS LINE" so that it refers to c1's field x rather than c2's, without changing the anonymous classes into named classes?
I realize this code is really ugly and it is not good programming style to use anonymous classes this way, but the code is being generated by another program, and this is the easiest way to implement the generator.