Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a syntax to get the reference to an anonymous inner class from a further anonymous inner class?

Consider this case:

public class SomeClass {
    public void someMethod() {
        new SomeInterface() {
              public void someOtherMethod() {
                  new SomeOtherInterface() {
                       new someThirdMethod() {
                            //My question is about code located here.
                       }
                  };
              }
        };
    }
}

Is there a syntax to reference the instance of the anonymous inner class represented by SomeInterface at the commented code? For SomeClass you can do SomeClass.this Is there an equivalent to get the implementation of SomeInterface?

If not, of course you can just define a final local variable in the SomeInterface implementation and reference it, but I was just wondering if there is in fact direct language support to reference the instance.

like image 207
Yishai Avatar asked May 28 '10 15:05

Yishai


1 Answers

The reason why SomeInterface.this doesn't compile is because the enclosing class is not SomeInterface, but rather some anonymous type.

You can't use qualified this with anonymous type. That's why they're anonymous; you can't refer to them by name, and qualified this works by explicitly naming an enclosing type.

It's tempting to try something like:

SomeClass$1.this

But then you get an error SomeClass$1 cannot be resolved to a type; despite the fact that if you let this code compile without this line, it will (in all likelihood) create a SomeClass$1.class.

You can either use a non-anonymous class and use qualified this, or you can use the final local variable technique you mentioned.

References

  • JLS 15.8.4 Qualified this
like image 72
polygenelubricants Avatar answered Sep 24 '22 20:09

polygenelubricants