问题
我有一个看起来像这样的Java程序。
public class LocalScreen {
public void onMake() {
aFuncCall(LocalScreen.this, oneString, twoString);
}
}
什么功能LocalScreen.this
的意思是aFuncCall
?
#1 热门回答(146 赞)
LocalScreen.this
引用封闭类的this
。
这个例子应该解释一下:
public class LocalScreen {
public void method() {
new Runnable() {
public void run() {
// Prints "An anonymous Runnable"
System.out.println(this.toString());
// Prints "A LocalScreen object"
System.out.println(LocalScreen.this.toString());
// Won't compile! 'this' is a Runnable!
//onMake(this);
// Compiles! Refers to enclosing object
onMake(LocalScreen.this);
}
public String toString() {
return "An anonymous Runnable!";
}
}.run();
}
public String toString() { return "A LocalScreen object"; }
public void onMake(LocalScreen ls) { /* ... */ }
public static void main(String[] args) {
new LocalScreen().method();
}
}
输出:
An anonymous Runnable!
A LocalScreen object
此帖已被重写为文章here。
#2 热门回答(50 赞)
它表示外部LocalScreen
类的this
实例。
如果没有限定符,则写入this
将返回该调用所在的inner class的实例。
#3 热门回答(13 赞)
编译器接受代码并使用它执行类似的操作:
public class LocalScreen
{
public void method()
{
new LocalScreen$1(this).run;
}
public String toString()
{
return "A LocalScreen object";
}
public void onMake(LocalScreen ls) { /* ... */ }
public static void main(String[] args)
{
new LocalScreen().method();
}
}
class LocalScreen$1
extends Runnable
{
final LocalScreen $this;
LocalScreen$1(LocalScreen $this)
{
this.$this = $this;
}
public void run()
{
// Prints "An anonymous Runnable"
System.out.println(this.toString());
// Prints "A LocalScreen object"
System.out.println($this.toString());
// Won't compile! 'this' is a Runnable!
//onMake(this);
// Compiles! Refers to enclosing object
$this.onMake($this);
}
public String toString()
{
return "An anonymous Runnable!";
}
}
正如你所看到的,当编译器接受内部类时,它会将其转换为外部类(这是一个很久以前的设计决策,因此不需要更改VM来理解内部类)。
当创建非静态内部类时,它需要对父类的引用,以便它可以调用外部类的方法/访问变量。
内部类的内部不是正确的类型,你需要访问外部类以获得调用onMake方法的正确类型。