我目前正在外部类中创建对此的显式引用,以便在匿名内部类中引用一个名称。有一个更好的方法吗?
Bill the Lizard
问问题
15826 次
3 回答
92
我最近才发现这个。使用OuterClassName.this
.
class Outer {
void foo() {
new Thread() {
public void run() {
Outer.this.bar();
}
}.start();
}
void bar() {
System.out.println("BAR!");
}
}
更新如果您只想要对象本身(而不是调用成员),那么Outer.this
就是要走的路。
于 2008-08-27T20:40:40.300 回答
19
采用EnclosingClass.this
于 2008-08-27T20:40:06.417 回答
1
您仍然可以使用 Outer.class 来获取外部类对象的类(它将返回与 Outer.this.getClass() 相同的 Class 对象,但效率更高)
如果要访问封闭类中的静态变量,可以使用 Outer.name ,其中 name 是静态字段或方法。
于 2008-09-16T15:18:44.197 回答