本文介绍了是否有一种语法可以从另一个匿名内部类中获取对匿名内部类的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

考虑这种情况:

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

是否存在引用匿名实例的语法在注释代码中由SomeInterface表示的内部类?对于SomeClass,你可以做 SomeClass.this 是否有相应的东西来获得SomeInterface的实现?

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?

如果没有,当然你可以在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.

推荐答案

SomeInterface.this 无法编译的原因是因为封闭类不是 SomeInterface ,而是一些匿名类型。

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

但是你得到一个错误 SomeClass $ 1无法解析为类型;尽管如果你让这段代码在没有这一行的情况下编译,它将(很可能)创建一个 SomeClass $ 1.class

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.

您可以使用非匿名类并使用合格的,也可以使用 final 你提到的局部变量技术。

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



这篇关于是否有一种语法可以从另一个匿名内部类中获取对匿名内部类的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 00:09