2010-04-28 15 views
57

Bir Java iç sınıfından this referansı almak mümkün mü?Dış sınıfın "bu" bir iç sınıftan nasıl erişilebilir?

Böyle dış sınıfın örneğini erişebilir

class Outer { 

    void aMethod() { 

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

cevap

6

Prepend bu dış sınıfının sınıf adı: evet yapabilirsiniz

outer.this 
1

ile dış sınıf adını kullanarak bu.

27

Outer.this

yani outer.this.

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

BTW Java sınıf adlarında kural gereği büyük harfle başlar.

İlgili konular