您可以直接使用简单名称调用该方法:
void fooBarMethod() {
otherMethod();
}
一旦在new FooBar()
匿名类中定义另一个名称为otherMethod()
的方法,该操作将失败。
Bar.this
是行不通的,因为它是一个没有名字的匿名类,在编译时给出了名称。它将得到一个类似于 Foo$1
的名称。所以你不能像 Bar.this
这样做。
好的,我已经编写了源代码:
class Bar { }
class FooBar { }
public class Demo {
public static void main() {
new Demo().method();
}
public void method() {
new Bar() {
void otherMethod() { System.out.println("Hello"); }
void barMethod() {
new FooBar() {
void fooBarMethod() {
otherMethod();
}
}.fooBarMethod();
}
}.barMethod();
}
}
生成的类文件如下所示:
Bar.class
FooBar.class
Demo.class
Demo$1.class // For `new Bar()` anonymous class
Demo$1$1.class // For `new FooBar()` anonymous class
现在,让我们直接转到new FooBar()
匿名类的字节码。该类将被命名为- Demo$1$1
。因此,运行javap
命令,我得到以下输出:
class Demo$1$1 extends FooBar {
final Demo$1 this$1;
Demo$1$1(Demo$1);
Code:
0: aload_0
1: aload_1
2: putfield #1
5: aload_0
6: invokespecial #2
9: return
void fooBarMethod();
Code:
0: aload_0
1: getfield #1
4: invokevirtual #3
7: return
}
那个
final
字段是指向
new Bar()
实例的引用副本。因此,
otherMethod()
在
this$1
引用上被调用,它是指向
new Bar()
匿名内部类实例的引用。你只是想要这样做,但由于这是一个匿名内部类,你无法直接访问
this
引用。但那是隐含的。
更详细的分析: