Yis*_*hai 5 java syntax anonymous-inner-class
考虑这种情况:
public class SomeClass {
public void someMethod() {
new SomeInterface() {
public void someOtherMethod() {
new SomeOtherInterface() {
new someThirdMethod() {
//My question is about code located here.
}
};
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
是否有语法引用注释代码中SomeInterface表示的匿名内部类的实例?对于SomeClass,你可以做到SomeClass.this
是否有相应的获得SomeInterface的实现?
如果没有,当然你可以在SomeInterface实现中定义一个最终的局部变量并引用它,但我只是想知道是否实际上有直接语言支持来引用该实例.
SomeInterface.this
不编译的原因是因为封闭类不是SomeInterface
,而是一些匿名类型.
您不能使用this
匿名类型的限定.这就是为什么他们是匿名的 ; 您不能通过名称来引用它们,也不能通过this
明确命名封闭类型来引用它们.
尝试类似的东西很诱人:
SomeClass$1.this
Run Code Online (Sandbox Code Playgroud)
但是你得到一个错误SomeClass$1 cannot be resolved to a type
; 尽管如果你让这段代码在没有这一行的情况下编译,它将(很可能)创建一个SomeClass$1.class
.
您可以使用非匿名类并使用qualified this
,也可以使用final
您提到的局部变量技术.