嗨,我正在创建一个类,在这个类中,我可以把函数传递下来,要么周期性地调用,要么一次性地调用。问题是,我传递的函数立即被调用,之后,当它们应该被调用时,我得到以下错误:
java.lang.NullPointerException
at TimedFunction$2.run(TimedFunction.java:41)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
基类如下(只有相关部分):
import java.util.concurrent.Callable;
...
public TimedFunction () {}
public void addSingleEvent (Callable func, int seconds){
//Convert to seconds from miliseconds
int time = seconds * 1000;
//Create a new timer
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
try {
func.call();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},
time
);
}
然后做一个测试类,看起来像这样:
public static void main(String[] args) {
// TODO Auto-generated method stub
TimedFunction tm = new TimedFunction();
tm.addSingleEvent(helloWorld(), 5);
tm.addRepeatedEvent(dataWorld(), 1);
}
private static Callable helloWorld() {
System.out.print("Hello world!");
System.out.print(" ");
return null;
}
检查您的helloWorld
方法-它返回null!
我觉得应该是
private static Callable helloWorld() {
return new Callable<String>() {
return "Hello world";
}
}
如果要我猜的话,我想你对如何使用lambas感到困惑。如果是这种情况,您的语法是错误的,它应该像这样:
tm.addSingleEvent(() -> "hello world", 5);
tm.addRepeatedEvent(() -> "data world", 1);