Reputation: 5669
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?
}
};
}
}
Upvotes: 79
Views: 27454
Reputation: 41
Extra: It is not possible when the inner class is declared 'static'.
Upvotes: 1
Reputation: 14656
You can access the instance of the outer class like this:
Outer.this
Upvotes: 113
Reputation: 199225
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.
Upvotes: 36