this 在 Java 中代表「當前物件引用」,但在內部類場景下,this 指向內部類實例,若需引用外部類實例,必須使用 外部類名.this 語法。本文系統解析 this 各種用法與邊界情況。
this.field = fieldthis(...) 必須為建構子第一行return thisother.method(this)public class Outer {
private String name = "Outer";
public void outerMethod() { System.out.println("Outer method"); }
class Inner {
private String name = "Inner";
public void innerMethod() {
System.out.println(name); // Inner
System.out.println(this.name); // Inner (this 指向 Inner 實例)
// System.out.println(Outer.this.name); // 正確訪問外部類
}
}
}
this → 當前內部類實例OuterClass.this → 外部類實例OuterClass.this.field → 訪問外部類成員OuterClass.this.method() → 調用外部類方法public class ThisDemo {
public static void main(String[] args) {
new Outer().demo();
}
}
class Outer {
public Outer() {
Inner inner = new Inner();
inner.callOuter(); // 內部類調用外部類方法
this.outerMethod(); // 外部類自身調用
}
public void outerMethod() { System.out.println("outer run"); }
class Inner {
public void callOuter() {
System.out.println("inner run");
Outer.this.outerMethod(); // 關鍵:Outer.this 訪問外部類
System.out.println("--------");
}
public void outerMethod() { System.out.println("inner outerMethod"); }
}
}
inner run outer run -------- outer run
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// this 指向匿名類實例
// OuterClass.this 指向外部類
OuterClass.this.handleClick();
}
});
關鍵差異:Lambda 沒有自己的 this,this 直接指向**外部類實例**(詞法作用域)。
public class LambdaThis {
String value = "Outer";
public void test() {
Runnable r = () -> {
System.out.println(this.value); // 直接訪問外部類,無需 LambdaThis.this
// this.toString() 呼叫外部類 toString()
};
r.run();
}
}
class Outer {
static class StaticInner {
void test() {
// 編譯錯誤:靜態內部類無外部類實例引用
// Outer.this.method();
}
}
}
Outer.thispublic class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
textView = findViewById(R.id.text);
// 匿名內部類中使用 MainActivity.this
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.updateText("Clicked!");
}
});
}
private void updateText(String msg) {
textView.setText(msg);
}
}
| 場景 | this 指向 | 訪問外部類 |
|---|---|---|
| 普通方法 | 當前實例 | N/A |
| 非靜態內部類方法 | 內部類實例 | Outer.this |
| 匿名內部類方法 | 匿名類實例 | Outer.this |
| Lambda 表達式 | 外部類實例 | 直接 this |
| 靜態內部類方法 | 內部類實例 | 不可訪問實例成員 |
理解 this 在不同嵌套層級的指向差異,是避免「誤訪問內部類成員」或「無法訪問外部類成員」的關鍵。核心口訣:內部類用 Outer.this,Lambda 直接用 this,靜態內部類無外部 this。Android 事件監聽、回調介面實現中尤為高頻,建議肌肉記憶。