2012-09-07 42 views
0

我需要使用內部類中外部類的指針this是否可以從嵌套類引用outter類指針?

我不知道如何去做,而不保存this指針。有其他選擇嗎?

class outerclass { 

    outerClass thisPointer; 

    outerclass() { 
     // 
     // NOTE: I am saving this pointer here to reference 
     // by the inner class later. I am trying to find 
     // a different alternative instead of saving this pointer. 
     // 
     thisPointer = this; 
    } 

    class innerClass { 

     void doSomething() { 

      // 
      // is there a way to reference the outter class 
      // without having to save the thisPointer from 
      // the outter class. 
      // NOTE someObject is a class outside of the 
      // outterclass control. 
      // 
      someObject.someMethod (thisPointer); 
     } 
    }  
} 
+0

Java的引用不是指針。 ;) –

回答

4

使用語法NameOfOuterClass.this

void doSomething() { 
    someObject.someMethod(outerClass.this); 
} 
+0

謝謝pb2q和RNJ回答。這就是訣竅。 – tadpole

1
outclass.this 

應該做的伎倆。

我假設你的外部類名是outerclass。按照慣例,你應該用大寫字母開始類名稱

如果我沒有正確理解你的例子,那麼這裏是一些示例代碼。這裏外部類(Test1)中的a的值被分配給內部類中的局部變量(Test2)

public class Test1 { 

    private int a =42;   

    private class Test2 { 

     public void a() { 
      int i = Test1.this.a; 
     } 
} 
相關問題