gpt4 book ai didi

java - classname.this.method 的引用是如何工作的?

转载 作者:行者123 更新时间:2023-11-30 07:04:42 28 4
gpt4 key购买 nike

例如,我有这段代码:

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 在那种情况下如何工作?我的意思是 - 它如何在匿名类中理解我想为 NewProjectModalWindowthis 实例调用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com