0

this内部クラスで外部クラスからのポインターを使用する必要があります。

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);
      }
  }     
}  
4

2 に答える 2

4

次の構文を使用しますNameOfOuterClass.this

void doSomething () {
    someObject.someMethod(outerClass.this);
}
于 2012-09-07T13:09:03.693 に答える
1
outclass.this 

トリックを行う必要があります。

あなたの外部クラス名はouterclassであると想定しています。Java の慣習により、クラス名は大文字で始める必要があります

あなたの例を正しく理解していない場合は、サンプルコードを次に示します。ここでは、外部クラス (Test1) の a の値が、内部クラス (Test2) のローカル変数に割り当てられています。

public class Test1  {

    private int a =42;         

    private class Test2 {

         public void a() {
             int i = Test1.this.a;
         }
}
于 2012-09-07T13:09:53.053 に答える