Java:类.this

标签 java class this

我有一个如下所示的 Java 程序。

public class LocalScreen {

   public void onMake() {
       aFuncCall(LocalScreen.this, oneString, twoString);
   }
}

LocalScreen.thisaFuncCall 中意味着什么?

最佳答案

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 .

关于Java:类.this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59482705/

相关文章:

ruby - Ruby 是否有类似于 Python 的正确运算符?

javascript - JS 文件中的函数不是由 index.js click evt 触发的

javascript - "this"在 ES6 的箭头函数中指的是什么?

java - 自定义 CursorAdapter 绑定(bind)到 simple_list_item_checked

java - 错误 : Cannot create TypedQuery for query with more than one return

Javascript import myClass from '/myClass.js' 在浏览器中不起作用

$(this) 上的 jquery 选择器

javascript - 将事件传递给回调函数

Tomcat 服务器上的 Java Servlet(找不到文件错误)

java - JSP调用servlet并转义注释