例如,我有以下代码:
public class NewProjectModalWindow extends Window
{
private void initComponents()
{
cancel = new Button("Cancel");
cancel.addClickListener(new Button.ClickListener()
{
@Override
public void buttonClick(ClickEvent event) {
NewProjectModalWindow.this.close();
}
});
}
}
在这种情况下this
如何工作?我的意思是 - 它如何在匿名类中理解我想要为 NewProjectModalWindow
的 this
实例调用 close
方法?
如何使用NewProjectModalWindow.this
在内存中的一堆对象中找到我的对象?
this
如何指向当前实例?
最佳答案
NewProjectModalWindow.this
引用匿名内部类的封闭实例,因此它引用创建 Button.ClickListener
实例的同一实例。
这是相关的 JLS entry :
15.8.4. Qualified this
Any lexically enclosing instance (§8.1.3) can be referred to by explicitly qualifying the keyword this.
Let T be the type denoted by TypeName. Let n be an integer such that T is the n'th lexically enclosing type declaration of the class or interface in which the qualified this expression appears.
The value of an expression of the form TypeName.this is the n'th lexically enclosing instance of this.
The type of the expression is T.
It is a compile-time error if the expression occurs in a class or interface which is not an inner class of class T or T itself.
关于java - classname.this.method 的引用是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27380933/