views:

173

answers:

4

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?
      }
    };

  }

}
+11  A: 

Like this:

outer.this
Guillaume
+4  A: 

Prepend the outer class's class name to this:

outer.this
staticman
+1  A: 

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

giri
+5  A: 

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