我有这个代码
private void startActionPerformed(java.awt.event.ActionEvent evt) {
this.start.setBackground(Color.green);
this.stop.setBackground(Color.lightGray);
if (!stopped) {
timer.cancel();
}
stopped = false;
stato.setText("Avviato");
timer = new Timer();
if(giacRitardo>0)
timer.schedule(S.run("argiacenze"), giacRitardo, giacRitardo);//parti dopo x secondi e itera ogni x secondi
if(cliRitardo>0)
timer.schedule(S.run("arclienti"), cliRitardo, cliRitardo);//parti dopo x secondi e itera ogni x secondi
//其他一些代码
和
class TaskSchedulato extends TimerTask {
@Override
public void run() {
redirectSystemStreams();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
URL sito = null;
try {
sito = new URL(sUrl + "?aggiornamento=arlingue");
} catch (MalformedURLException ex) {
System.out.println("Indirizzo del sito mal formato o inesistente");
}
URLConnection yc = null;
try {
yc = sito.openConnection();
} catch (IOException ex) {
System.out.println("Errore di connessione _ ");
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (IOException ex) {
Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
dataErrore = new Date();
System.out.println(sdf.format(dataErrore));
System.out.println("Errore di connessione: " + dataErrore);
}
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
和
TaskSchedulato S = new TaskSchedulato();
我需要扩展上面的方法 run,以便我可以向它传递一个字符串参数。 怎样才能做到呢。 我几乎是java的新手。所以,请原谅我的经验不足。
实际上我收到了错误: 找不到适合 run(String) 的方法 方法 TimerTask.run() 不适用 (实际参数列表和正式参数列表的长度不同) 方法 MainForm.TaskScheduato.run() 不适用 (实际参数列表和正式参数列表的长度不同)
提前谢谢
最佳答案
这可以通过 method overloading 轻松实现.
简而言之,方法重载是一种语言功能,允许声明多个具有相同名称但参数不同的方法。
应用于您的问题,无需重写父级的 run()
方法,只需声明另一个 run()
方法,如下所示:
public void run(String someInput) {
/* ... */
}
当然,如果这对您的程序有意义,您可以从 run(String)
内部调用 run()
:
public void run(String someInput) {
/* Do something with someInput */
run(); // Hand over to parent's run() method
/* Maybe do some other stuff */
}
根据您想要执行的操作,您可能想要同时使用方法重载和重写。需要更多背景信息才能提供更具体的建议。
关于java - 如何扩展 TimerTask 中的方法运行。必须接受字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43145976/