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

孤街浪徒 提交于 2019-12-06 03:09:56

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2930327/is-there-a-syntax-to-get-the-reference-to-an-anonymous-inner-class-from-a-furthe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!