为什么我的计时器在方法调用中没有重置为null

yduiuuwa  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(300)

在我的代码中,我必须使用多个计时器/延迟。
所以我想创建一个重置计时器的方法。但计时器从来没有重置为空,我不知道为什么不。如果有人能告诉我为什么我的计时器在第二个例子中从来没有被重置为空它将不胜感激!
工作原理:

public class BIhcsTemplate extends BComponent implements Runnable {

                Clock.Ticket delayTimer; //simple clock from a library

                public void onExecute() throws Exception {

               // if true reset timer
                if (getBExample()){
                  if(delayTimer!=null){              
                  delayTimer.cancel();                        
                  delayTimer=null;}
            }

               if (delayTimer==null){
              //start the timer
      }
 }

我想做但不起作用的事情:

public class BIhcsTemplate extends BComponent implements Runnable {

                Clock.Ticket delayTimer; //simple clock from a library

                public void onExecute() throws Exception {

                if (getBExample()){ 
               resetTimer(delayTimer)       
               }
               if (delayTimer=null){
               //start timer}
               }
            }

       public void resetTimer(Clock.Ticket timerToReset){        
       if(timerToReset!=null){               
       timerToReset.cancel();              
       timerToReset=null; // <== assigned value null is never used according to intellij        
      }}
9gm1akwq

9gm1akwq1#

基本上,所发生的事情是向方法发送一个指向对象的指针,但这是一个新的对象引用。然后将该副本设置为null,但原始对象没有更改,只是您在其中的引用更改为null。所以你可以:

public Clock.Ticket resetTimer(Clock.Ticket timerToReset){        
    if(timerToReset!=null){               
       timerToReset.cancel();              
       timerToReset=null;  
    }
    return timerToReset;
 }

然后将其用作:

delayTimer=resetTimer(delayTimer)

关于这个问题的更多信息:java是“按引用传递”还是“按值传递”?

相关问题