是否可以从嵌套类引用外部类指针?

时间:2012-09-07 13:06:29

标签: java this

我需要使用内部类外部类的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);
      }
  }     
}  

2 个答案:

答案 0 :(得分:4)

使用语法NameOfOuterClass.this

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

答案 1 :(得分: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;
         }
}
相关问题