Access to an external class field

How do I access the field of an outer class, given the reference to the object of the inner class?

class Outer { int field; class Inner { void method(Inner parameter) { // working on the current instance is easy :) field = 0; Outer.this.field = 1; // working on another instance is hard :( parameter.field = 2; // does not compile parameter.Outer.this.field = 3; // does not compile parameter.outer().field = 4; // This works... } // ...but I really don't want to have to write this method! Outer outer() { return Outer.this; } } } 

I also tried Outer.parameter.field and many other options. Is there any syntax that does what I want?

+7
source share
3 answers

There are two ways to look at what you are doing as a static method or as a non-static method.

At first glance, your example is more like a static method, since it controls the state of the parameter, rather than its own state. The static problem has been addressed before, for example, see In Java, how do I access the outer class when I'm not in the inner class?

But your example is a non-stationary method, and I think I see what you get and why you think that an external link should be possible. In the end, there are other situations in which you can access the implementation details of other instances of your own type - for example, it is common to refer to the fields of a private member of an input parameter when overriding equal. Unfortunately, I just don't think java provides a way to refer to another lexically spanning instance. This is likely due to the way Java actually implements non-static inner classes . Java uses this$0 for its own purposes, but you do not have access to this synthetic field.

+2
source

From outside the inner class, I believe that there is no way to refer to the inner instance of the class to refer to members of the outer instance of the class. From within a non-static inner class, you can, of course, reference them using the Outer.this.* Syntax.

Think of it this way: the inner class is actually a completely separate class. It has a compiler-generated field (usually called something strange, like this$0 ). Inside the inner class, the language allows you to reference this field using Outer.this ; however, that syntactic sugar is not available outside the innermost class. Also, the compiler is not generated.

+8
source

How about this solution:

 class Outer { int field; class Inner { final Outer outer = Outer.this; void method(Inner parameter) { // working on the current instance is easy :) field = 0; Outer.this.field = 1; // working on another instance: parameter.outer.field = 2; } } } 
+8
source

All Articles