77

Is it possible to get a reference to this from within a Java inner class?

i.e.

class Outer {

  void aMethod() {

    NewClass newClass = new NewClass() {
      void bMethod() {
        // How to I get access to "this" (pointing to outer) from here?
      }
    };
  }
}
skiphoppy
  • 97,646
  • 72
  • 174
  • 218
llm
  • 5,539
  • 12
  • 36
  • 30

5 Answers5

109

You can access the instance of the outer class like this:

Outer.this
Guillaume
  • 14,306
  • 3
  • 43
  • 40
35

Outer.this

ie.

class Outer {
    void aMethod() {
        NewClass newClass = new NewClass() {
            void bMethod() {
                System.out.println( Outer.this.getClass().getName() ); // print Outer
            }
        };
    }
}

BTW In Java class names start with uppercase by convention.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
10

Prepend the outer class's class name to this:

outer.this
staticman
  • 728
  • 5
  • 9
3

yes you can using outer class name with this. outer.this

giri
  • 26,773
  • 63
  • 143
  • 176
1

Extra: It is not possible when the inner class is declared 'static'.