是否可以从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?
}
};
}
}
是否可以从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?
}
};
}
}
可以访问外部类的实例是这样的:
Outer.this
前面加上外部类的类名来此:
outer.this
是的,你可以使用外部类名称这个。 outer.this
Outer.this
即。
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
System.out.println(Outer.this.getClass().getName()); // print Outer
}
};
}
}
BTW在Java中,类名以大写字母开头。