Java内部类是否可以获取到对this
的引用?
例如:
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
// How to I get access to "this" (pointing to outer) from here?
}
};
}
}
Java内部类是否可以获取到对this
的引用?
例如:
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
// How to I get access to "this" (pointing to outer) from here?
}
};
}
}
您可以通过以下方式访问外部类的实例:
Outer.this
Outer.this
即:
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
System.out.println( Outer.this.getClass().getName() ); // print Outer
}
};
}
}
顺便提一句,在Java中,按照惯例,类名以大写字母开头。
在这个前面加上外部类的类名:
outer.this
是的,你可以使用外部类名和this关键字。 outer.this
额外说明:当内部类被声明为“静态”时,就不可能实现该功能。