Java 保持对';这';内部运行方法
我用一个匿名的“具体”类将Java 保持对';这';内部运行方法,java,Java,我用一个匿名的“具体”类将TimerTask子类化,如下所示: public void setTimedTask() { /* Note: 'this' implements an interface called UpdateIndicatorsReceiver */ final UpdateIndicatorsReceiver receiver = this; final TimerTask timerTask = new TimerTask() {
TimerTask
子类化,如下所示:
public void setTimedTask() {
/* Note: 'this' implements an interface called UpdateIndicatorsReceiver */
final UpdateIndicatorsReceiver receiver = this;
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
/* The interface UpdateIndicatorsReceiver has an updateIndicators method */
receiver.updateIndicators();
}
};
/* Code to actually set the timer.... */
}
请注意,声明一个名为
receiver
的本地final
字段并将其设置为this
的奇怪之处。为了在匿名类的run
方法中使用它,是否有更干净的方法获取对this
的不更改引用?UpdateIndicatorsReceiver.this.updateIndicators()代码>这应该是不必要的;您只需直接调用updateIndicators()
i、 e:
无需接收器
参考。这为我编译。编译器告诉我“在作用域中无法访问UpdateIndicatorsReceiver类型的封闭实例”。编辑:但我可以使用“this”的实际类,它可以工作。不知道如何获取封闭类的“this”引用,谢谢。在最终阅读了一些备选方案后,我会接受这个答案。是的,您可能需要使用ConcreteClass.this.updateIndicators()代码>:-)我接受了另一个答案,但如果可以的话,我也会接受你的答案。谢谢你的建议,快乐编码。我也是。我真的应该回顾内部类和匿名内部类。我总是对它有点困惑(尤其是当它们带有“static”、“final”之类的词时),它们是Java唯一的难点,至少对我来说是这样。
public void run() {
updateIndicators();
}