有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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的不更改引用


共 (2) 个答案

  1. # 1 楼答案

    这应该是不必要的;你只需要直接调用updateIndicators()

    即:

    public void run() {
        updateIndicators();
    }
    

    不需要receiver引用。这是为我编写的

  2. # 2 楼答案

    UpdateIndicatorsReceiver.this.updateIndicators();