2010-04-28 108 views
57

是否可以从Java内部类中获取对this的引用?如何从内部类访问外部类的“this”?

class Outer { 

    void aMethod() { 

    NewClass newClass = new NewClass() { 
     void bMethod() { 
     // How to I get access to "this" (pointing to outer) from here? 
     } 
    }; 
    } 
} 

回答

71

可以访问外部类的实例是这样的:

Outer.this 
6

前面加上外部类的类名来此:

outer.this 
1

是的,你可以使用外部类名称这个outer.this

27

Outer.this

即。

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

BTW在Java中,类名以大写字母开头。