是否可以this
从 Java 内部类中获取引用?
IE
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
// How to I get access to "this" (pointing to outer) from here?
}
};
}
}
是否可以this
从 Java 内部类中获取引用?
IE
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
// How to I get access to "this" (pointing to outer) from here?
}
};
}
}
您可以像这样访问外部类的实例:
Outer.this
外部.this
IE。
class Outer {
void aMethod() {
NewClass newClass = new NewClass() {
void bMethod() {
System.out.println( Outer.this.getClass().getName() ); // print Outer
}
};
}
}
顺便说一句,在 Java 中,类名按约定以大写开头。
将外部类的类名添加到此:
outer.this
是的,您可以将外部类名与this一起使用。 外部.this
额外:当内部类被声明为“静态”时,这是不可能的。