我创建了一段代码,它获取一个 IP 地址(来自另一个类中的 main 方法),然后循环遍历一系列 IP 地址,并在执行过程中对每个 IP 地址进行 ping 操作。我有一个 GUI 前端,它崩溃了(因此我做了多线程。我的问题是我不能再将 IP 地址作为我的 ping 代码中的参数作为它的可调用参数。我已经搜索过为此,似乎无法找到解决此问题的方法。有没有办法让可调用的方法接受参数?如果没有,还有其他方法可以完成我想要做的事情吗?
我的代码示例:
public class doPing implements Callable<String>{
public String call() throws Exception{
String pingOutput = null;
//gets IP address and places into new IP object
InetAddress IPAddress = InetAddress.getByName(IPtoPing);
//finds if IP is reachable or not. a timeout timer of 3000 milliseconds is set.
//Results can vary depending on permissions so cmd method of doing this has also been added as backup
boolean reachable = IPAddress.isReachable(1400);
if (reachable){
pingOutput = IPtoPing + " is reachable.\n";
}else{
//runs ping command once on the IP address in CMD
Process ping = Runtime.getRuntime().exec("ping " + IPtoPing + " -n 1 -w 300");
//reads input from command line
BufferedReader in = new BufferedReader(new InputStreamReader(ping.getInputStream()));
String line;
int lineCount = 0;
while ((line = in.readLine()) != null) {
//increase line count to find part of command prompt output that we want
lineCount++;
//when line count is 3 print result
if (lineCount == 3){
pingOutput = "Ping to " + IPtoPing + ": " + line + "\n";
}
}
}
return pingOutput;
}
}
IPtoPing 曾经是采用的参数。
最佳答案
您不能将它作为参数传递给 call()
,因为方法签名不允许这样做。
但是,您可以将必要的信息作为构造函数参数传递;例如
public class DoPing implements Callable<String>{
private final String ipToPing;
public DoPing(String ipToPing) {
this.ipToPing = ipToPing;
}
public String call() throws SomeException {
InetAddress ipAddress = InetAddress.getByName(ipToPing);
....
}
}
(我已经纠正了几个严重的代码风格违规!!)
有一些方法可以消除上面的一些“样板”编码(参见其他一些答案)。在这种情况下,我们谈论的是 4 行代码(在大约 40 行的类中),所以我不相信这值得付出努力。 (但是,嘿,这是你的代码。)
或者,您可以:
将 DoPing 声明为内部类(或 lambda)并让它引用封闭范围内的
final ipToPing
,或添加一个
setIpToPing(String ipToPing)
方法。
(最后一个允许重用 DoPing
对象,但缺点是您需要同步才能线程安全地访问它。)
关于java - 有没有办法在可调用方法中接受参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9992992/