如何添加方法调用者的引用?

时间:2015-01-02 04:52:28

标签: java

好吧,我想不出一个更好的标题来解决我的问题。

我有一个计时器线程。它滴答作响,经过足够的滴答后,我想让它调用一个调用它的方法。如果有人曾经使用过Unity,我正试图这样做:

public void test(String CallMeLater){
   Invoke(CallMeLater);  // Unity
   caller.CallMeLater(); // Idea
}

值得注意的是,调用它并不是静态的。 我该怎么做?

这就是我所拥有的:

CLOCK

public class Clock extends Thread {
   Object test;

   public Clock(int minutes, Object test) {
      this.minutes = minutes;
      this.test = test;
   }

   public void run() {
      try {
         Thread.sleep(1000);
      } catch(Exception err) {}

      test.SayHi();
      run();
   }
}

CALLER

public class MainWindow {
   // When the Clock is created i want to pass "this" into it.
   app.Clock clock = new app.Clock(60, this); 

   public MainWindow(){
      // Creates frame, and add listeners. I cut it out. 
      // It has nothing to do with the problem at hand
   }

   private void Set(){
      // This is where i start the timer
      clock.start();  
   }

   public void SayHi(){
      System.out.println("Hi");
   }
}

1 个答案:

答案 0 :(得分:1)

回调是接口的一个很好的用例。

public Inteface Callback {
    public void complete();
}

public class Ticker {
    public void test(Callback callback) {
        // tick, tick, tick
        callback.complete();
    }
}

public class User implements Callback {
    public void complete() {
        ...
    }

    public void useTicker() {
        Ticker ticker = new Ticker();
        ticker.test(this);
    }
}

请注意,Java有许多内置接口,看起来与此完全相同。事实上,Timer类有一个很好的例子:TimerTask,它可以完全满足您的需求。