这只是一个知识/好奇心问题。
在Java中工作了几年后,这才让我意识到。
class Foo {
class Bar{
Foo.this.doSomething();
}
}
当我看到
Foo.this
时,我会认为它是一个静态引用,但实际上不是这样。我知道这是Java规范的一部分,但使用
<Class>.this
时究竟发生了什么?这是其中的一个"它就是这个样子"的事情。
这只是一个知识/好奇心问题。
在Java中工作了几年后,这才让我意识到。
class Foo {
class Bar{
Foo.this.doSomething();
}
}
Foo.this
时,我会认为它是一个静态引用,但实际上不是这样。<Class>.this
时究竟发生了什么?Bar
中的一个“隐藏”字段。通过反编译,你可以最容易地看到这一点。你会看到有一个Bar
构造函数,它接受一个对Foo
实例的引用。该引用存储在一个字段中,然后当你使用Foo.this
时,它只是访问该字段。因此,假设你将Foo.this.doSomething()
放入一个someMethod
调用中,你的代码类似于:class Foo {
static class Bar {
private final Foo $foo;
Bar(Foo foo) {
this.$foo = foo;
}
public void someMethod() {
$foo.doSomething();
}
}
}