我有一个课程如下:
private class LanePair {
public int cameraNumber;
public Nest nest1, nest2;
public LanePairStatus status = LanePairStatus.TIMER_OFF;
Timer timer = new Timer();
public LanePair(int cameraNunber, Nest nest1, Nest nest2) {
this.cameraNumber = cameraNumber;
this.nest1 = nest1;
this.nest2 = nest2;
}
public void startTimer() {
status = LanePairStatus.TIMER_ON;
timer.schedule(new TimerTask() {
public void run() {
DoAskForLaneClear(/*I want to pass this class (LanePair) here*/);
}
}, 6000 ); // 6 seconds
}
public void stopTimer() {
timer.cancel();
}
}
问题是,我无法弄清楚如何做到这一点。有什么建议吗?
答案 0 :(得分:10)
DoAskForLaneClear(LanePair.this);
由于您无法使用this
(它将引用TimerTask
),但您的匿名类不能存在于LanePair
的实例中,该实例由{引用{1}}
答案 1 :(得分:0)
我想你想要
DoAskForLaneClear(this);
或
this.DoAskForLaneClear();
我没有看到DoAskForLaneClear()的定义在哪里。
答案 2 :(得分:0)
我有时会这样做:
public void startTimer() {
status = LanePairStatus.TIMER_ON;
**final LanePair lanePairRef = this;**
timer.schedule(new TimerTask() {
public void run() {
DoAskForLaneClear(**lanePairRef**);
}
}, 6000 ); // 6 seconds
}
答案 3 :(得分:0)
如果你想在任何情况下使用这个字,例如:)
import java.util.Timer;
import java.util.TimerTask;
public class Test
{
public void doAskForLaneClear(LanePair lanePair){
//Action of lanePair
}
private class LanePair {
public int cameraNumber;
public Nest nest1, nest2;
public LanePairStatus status = LanePairStatus.TIMER_OFF;
Timer timer = new Timer();
public LanePair(int cameraNumber, Nest nest1, Nest nest2) {
this.cameraNumber = cameraNumber;
this.nest1 = nest1;
this.nest2 = nest2;
startTimer();
}
public void startTimer() {
status = LanePairStatus.TIMER_ON;
timer.schedule(new MyTimerTask(this), 6000 ); // 6 seconds
}
public void stopTimer() {
timer.cancel();
}
}
private class MyTimerTask extends TimerTask{
private LanePair lanePair;
public MyTimerTask(LanePair lanePair){
this.lanePair = lanePair;
}
@Override
public void run() {
Test.this.doAskForLaneClear(lanePair);
}
}
}
答案 4 :(得分:-1)
LanePair.class