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

标签 java this

例如,我有以下代码:

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/

相关文章:

java - 如何在响应式网页中为一行使用单个网页元素

java - 查找字典单词的变位词

Javascript "this"范围根据调用方式给出不同的结果

java - "this"在 Java 中做什么?

Javascript 将 this 传递给函数

java - 测试时忽略 Spring Controller 上的 PreAuthorize 注释

android - IllegalStateExecption Android studio Webview 应用程序

Java 在没有正则表达式的情况下从 String 中删除 HTML

C++ 在非成员函数中无效使用 'this'

javascript - 在函数内使用 "this"关键字访问全局属性