可调用类给出错误:doPing不是抽象的,不会覆盖抽象方法call()?

时间:2012-04-02 14:52:26

标签: java multithreading callable

在尝试创建可调用类时,我似乎遇到了上述错误。我搜索了原因,但似乎找不到任何东西。 NetBeans为我提供了一些抽象的选项,但我是新手,我宁愿找出原因发生的原因。有人能说清楚这个吗?

public class doPing implements Callable<String>{

    public String call(String IPtoPing) 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;
    }
}

3 个答案:

答案 0 :(得分:2)

在您的代码中,call方法有一个参数:它不会覆盖call接口的Callable方法 - 它应该如下所示:

public String call() throws Exception{ //not public String call(String IPtoPing)

}

如果您使用的是Java 6+,最好使用Override注释,这可以帮助发现错误的方法签名(在这种情况下,您已经有编译错误):

@Override
public String call() throws Exception{
}

答案 1 :(得分:1)

您的'doPing'类定义为implements Callable<String>。这意味着它应该实现不接受任何参数的call()方法。以下是Callable

的定义
public interface Callable<V> {
    V call() throws Exception;
}

如果您希望String IPtoPingdoPing,则需要删除Callable参数:

public class doPing implements Callable<String> {
     // you need to define this method with no arguments to satisfy Callable
     public String call() throws Exception {
         ...
     }
     // this method does not satisfy Callable because of the IPtoPing argument
     public String call(String IPtoPing) throws Exception {
         ...
     }
}

答案 2 :(得分:1)

Callable界面要求您使用call()方法。但是你的方法是
 call(String ipToPing)

考虑添加setIpToPing(String ip)方法来设置正确的IP。

doPing myCallable = new doPing();//Note doPing should be called DoPing to keep in the java naming standards.
myCallable.setIpToString(ip);//Simple setter which stores ip in myCallable
myCallable.call();