gpt4 book ai didi

java - 如何在 Java 中将函数作为参数传递给 Callable

转载 作者:行者123 更新时间:2023-11-29 10:01:03 27 4
gpt4 key购买 nike

我有一个函数可以对我不想更改的数据库进行一些服务调用。但是如果有多个请求需要运行这个函数,我想在一个线程池中运行它们。所以,我想弄清楚如何将这个函数包装在 Callable 类中。这是函数的签名:

void invokeCommand(string table, int ctype)

The function invokeCommand does not return any value but can throw an exception. I suppose using the following construct is not an option since I have no way of passing parameters and the invokeCommand function to this.

Callable<Void> myCommand = new Callable<Void>() {
public Void call() {
...
}
}

我了解到另一种方法是定义一个命名类而不是匿名类,并通过构造函数传递参数 (string, int)。有没有办法我也可以传递函数 invokeCommand?实现这一目标的推荐方法是什么?提前致谢。

最佳答案

匿名类可以访问在它们之外声明的final 变量。他们还可以访问封闭类的成员变量。

final String table = ...;
final int ctype = ...;
Callable<Void> myCommand = new Callable<Void>() {
public Void call() {
invokeCommand(table, ctype);
return null;
}
};

在 Java 8 中,这个限制被放宽了——变量不需要声明为 final,但它必须是有效的 final。如果一个变量在声明后从未被赋值,则它实际上是最终的。

关于java - 如何在 Java 中将函数作为参数传递给 Callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com