I have a class as follows:
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.camera开发者_开发知识库Number = 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();
}
}
The thing is, I can't figure out how to do it. Any suggestions?
Related:
- How do you get a reference to the enclosing class from an anonymous inner class in Java?
- Getting hold of the outer class object from the inner class object
DoAskForLaneClear(LanePair.this);
Since you can't use this
(it will reference the TimerTask
), but your anonymous class can't exist wihtout an instance of LanePair
, that instance is referenced by LanePair.this
I think you want either
DoAskForLaneClear(this);
or
this.DoAskForLaneClear();
I don't see where DoAskForLaneClear() is defined though.
I do this sometimes:
public void startTimer() {
status = LanePairStatus.TIMER_ON;
**final LanePair lanePairRef = this;**
timer.schedule(new TimerTask() {
public void run() {
DoAskForLaneClear(**lanePairRef**);
}
}, 6000 ); // 6 seconds
}
If you want to use in any case this word for example :)
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);
}
}
}
LanePair.class
?
精彩评论