java是一种正确的匿名子类化TimerTask的方法,在run方法中保留对“this”的引用
我用一个匿名的“具体”类将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
,有没有更干净的方法来获取对this
的不更改引用
# 1 楼答案
这应该是不必要的;你只需要直接调用
updateIndicators()
即:
不需要
receiver
引用。这是为我编写的# 2 楼答案
UpdateIndicatorsReceiver.this.updateIndicators();