Well, you can't do that directly, as there is no such way defined in Java language. However, you can use some reflection hack to get the value of that field.
Basically, the inner classes store a reference to the enclosing class in the field named this$0
. You can find more detail in this other post on SO.
Now, using reflection, you can access that field, and get the value of any attribute for that field:
class A {
public int a;
public A(int a) { this.a = a; }
public class B {
public int b;
public B(int b) { this.b = b; }
public void foo(B other) throws Exception {
A otherA = (A) getClass().getDeclaredField("this$0").get(other);
System.out.println(otherA.a);
System.out.println(other.b);
}
}
}
public static void main (String [] args) throws Exception {
A.B obj1 = new A(1).new B(1);
A.B obj2 = new A(2).new B(2);
obj2.foo(obj1);
}
This will print 1, 1
.
But as I said, this is just a hack. You wouldn't want to write such a code in real application. Rather you should go with a cleaner way as depicted in @dashblinkenlight's answer.