Java: Class.this

2022-08-31 08:44:04

我有一个Java程序,看起来像这样。

public class LocalScreen {

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

在 中是什么意思?LocalScreen.thisaFuncCall


答案 1

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

这篇文章已经重写为一篇文章在这里


答案 2

它表示外部类的实例。thisLocalScreen

不带限定符的写入将返回调用所在的内部类的实例。this