Is there a way to take an argument in a callable method?

后端 未结 7 1019
Happy的楠姐
Happy的楠姐 2020-12-23 16:41

I have created a piece of code which takes an IP address (from main method in another class) and then loops through a range of IP addresses pinging each one as it goes. I ha

7条回答
  •  时光说笑
    2020-12-23 17:04

    You can't pass it as the argument to call() because the method signature doesn't allow it.

    However, you can pass it as a constructor argument; e.g.

    public class DoPing implements Callable{
        private final String ipToPing;
    
        public DoPing(String ipToPing) {
            this.ipToPing = ipToPing;
        }
    
        public String call() throws SomeException {
            InetAddress ipAddress = InetAddress.getByName(ipToPing);
            ....
        }
    }
    

    (I've corrected a couple of egregious code style violations!!)

    Alternatively, you could:

    • declare DoPing as an inner class and have it refer to a final ipToPing in the enclosing scope, or

    • add a setIpToPing(String ipToPing) method.

    (The last allows a DoPing object to be reused, but the downside is that you will need to synchronize to access it thread-safely.)

提交回复
热议问题