Won*_*abo 4 java anonymous-inner-class anonymous-class inner-classes
我有以下代码:
public class Bar {}
public class FooBar {}
public class Foo {
public void method() {
new Bar() {
void otherMethod() { }
void barMethod() {
new FooBar() {
void fooBarMethod() {
Bar.this.otherMethod(); // not compiles
}
};
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
所以我有一个匿名内部类,其中有另一个匿名内部类.问题:有没有办法Bar
从内部内部类访问外部内部类的方法FooBar
?
您可以使用简单名称直接调用该方法:
void fooBarMethod() {
otherMethod(); // compiles
}
Run Code Online (Sandbox Code Playgroud)
这将失败,你定义一个名字的另一种方法的时刻otherMethod()
在new FooBar()
匿名类.
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(); // not compiles
}
}.fooBarMethod();
}
}.barMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
生成的类文件将是:
Bar.class
FooBar.class
Demo.class
Demo$1.class // For `new Bar()` anonymous class
Demo$1$1.class // For `new FooBar()` anonymous class
Run Code Online (Sandbox Code Playgroud)
现在,让我们直接进入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 // Field this$1:LDemo$1;
5: aload_0
6: invokespecial #2 // Method FooBar."<init>":()V
9: return
void fooBarMethod();
Code:
0: aload_0
1: getfield #1 // Field this$1:LDemo$1;
4: invokevirtual #3 // Method Demo$1.otherMethod:()V
7: return
}
Run Code Online (Sandbox Code Playgroud)
该final
字段有一个对new Bar()
实例的引用副本.因此,在otherMethod()
引用上调用它this$1
,它是对new Bar()
匿名内部类的实例的引用.好吧,你只是试图这样做,但由于这是一个匿名的内部类,你不能this
直接访问引用.但是,这隐含在那里.
有关更详细的分析:
归档时间: |
|
查看次数: |
138 次 |
最近记录: |