且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法在可调用方法中接受参数?

更新时间:2022-04-15 00:54:54

你不能把它作为参数传递给 call() 因为方法签名不允许它.

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

但是,您可以将必要的信息作为构造函数参数传递;例如

However, you can pass the necessary information as a constructor argument; e.g.

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);
        ....
    }
}

(我已经纠正了一些严重的代码风格违规!!)

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

有一些方法可以消除一些样板"在上面编码(请参阅其他一些答案).在这种情况下,我们谈论的是 4 行代码(在大约 40 行的类中),所以我不相信这是值得的.(但是,嘿,这是您的代码.)

There are ways to eliminate some of the "boilerplate" coding in the above (see some of the other answers). In this case we are talking about 4 lines of code (in a ~40 line class), so I am not convinced that it is worth the effort. (But hey, it is your code.)

或者,您可以:

  • 将 DoPing 声明为内部类(或 lambda)并让它引用封闭范围内的 final ipToPing,或

添加一个 setIpToPing(String ipToPing) 方法.

(最后一个允许重用 DoPing 对象,但缺点是您需要同步以线程安全地访问它.)

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