![](/img/trans.png)
[英]How to Invoke a method that take a Callable Interface or method as parameter with java reflection
[英]Is there a way to take an argument in a callable method?
我创建了一段代码,它获取一个 IP 地址(来自另一个类中的 main 方法),然后循环遍历一系列 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
对象,但缺点是您需要同步以线程安全地访问它。)
添加到 Jarle 的答案 - 如果您将Callable
创建为匿名类的实例,则可以使用匿名类之外的final
字段将数据传递到实例中:
final int arg = 64;
executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return arg * 2;
}
});
您不能将参数传递给call()
因为方法签名不允许它但这里至少有一种方法可以解决这个问题
Callable
和call()
定义一个抽象类:
import java.util.concurrent.Callable;
public abstract class Callback<T> implements Callable<Void> {
T result;
void setResult (T result) {
this.result = result;
}
public abstract Void call ();
}
定义应该触发回调的方法:
public void iWillFireTheCallback (Callback callback) {
// You could also specify the signature like so:
// Callback<Type of result> callback
// make some information ("the result")
// available to the callback function:
callback.setResult("Some result");
// fire the callback:
callback.call();
}
在您要调用iWillFireTheCallback
的地方:
定义回调函数(甚至可能在方法内部):
class MyCallback extends Callback {
@Override
public Void call () {
// this is the actual callback function
// the result variable is available right away:
Log.d("Callback", "The result is: " + result);
return null;
}
}
然后在传入回调时调用iWillFireTheCallback
:
iWillFireTheCallback(new MyCallback());
创建 doPing 类时(类名中应该是大写字母),在构造函数中发送 ip-address。 在 call-method 中使用这个 ip-address。
在doPing
类中放置一些( final
)字段,以及初始化它们的构造函数,然后将要在call()
使用的值传递给doPing
的构造doPing
:
public class DoPing implements Callable<String> {
private final String ipToPing;
public DoPing(String ip) {
this.ipToPing = ip;
}
public String call() {
// use ipToPing
}
}
你必须defien属性,如ipAddress
和其存取方法。 并在constructor
或setter
方法中传递其值。 在doPing
类使用ipAddress
属性。
class DoPing/* In java all classes start with capital letter */implements Callable<String>
{
private String ipAddress;
public String getIpAddress()
{
return ipAddress;
}
public void setIpAddress(String ipAddress)
{
this.ipAddress = ipAddress;
}
/*
* Counstructor
*/
public DoPing(String ipAddress )
{
this.ipAddress = ipAddress;
}
@Override
public String call() throws Exception
{
// your logic
}
}
并非总是可以引用(有效)最终变量以将其值用作“参数”,但您可以自己制定舒适的通用解决方案。 首先定义这个功能接口:
@FunctionalInteface
interface CallableFunction<T, R> {
public abstract R call(T arg) throws Exception;
public static <T, R> Callable<R> callable(CallableFunction<T, R> cf, T arg) {
return () -> cf.call(arg);
}
}
这个函数式接口提供了静态方法callable
,它创建了一个Callable
实例,它简单地使用提供的参数(T 类型)调用call(T)
T)。 然后你需要你的DoPing
类来实现CallableFunction
像这样:
public class DoPing implements CallableFunction<String, String> {
@Override
public String call(final String ipToPing) throws Exception {
final var ipAddress = InetAddress.getByName(ipToPing);
final var reachable = ipAddress.isReachable(1400);
String pingOutput = null;
if (reachable) {
pingOutput = ipToPing + " is reachable.\n";
}
else {
final var ping = Runtime.getRuntime().exec("ping " + ipToPing + " -n 1 -w 300");
try (var in = new BufferedReader(new InputStreamReader(ping.getInputStream()))) {
String line;
for (int lineCount = 1; (line = in.readLine()) != null; ++lineCount) {
if (lineCount == 3) {
pingOutput = "Ping to " + ipToPing + ": " + line + "\n";
break;
}
}
}
}
return pingOutput;
}
在这里,我们将call
签名更改为接受String
参数,并且现在它实现了CallableFunction
而不是像以前那样Callable
。 其他更改很小,但值得一提的是,我们通过在BufferedReader
上使用 try-with-resource 来防止资源泄漏,并且还向输入收集循环添加了break
(从while
更改为for
)以尽可能快地终止。
现在你可以像这样使用代码:
final var ping = CallableFunction.callable(new DoPing(), "127.0.0.1");
final var task = new FutureTask<>(ping);
new Thread(task).start();
System.out.println(task.get(20, TimeUnit.SECONDS));
您还可以在需要时在其他情况下重用CallableFunction
。
我知道现在回答这个问题太晚了,考虑到它已经有 8 年历史了,但在 15 天(!)前活跃,我觉得这仍然会对使用 Java 8 及更高版本的人有所帮助。
PS,这只是 Victor Sorokin 可能通过 lambdas 回答的语法糖。
public static Callable<String> generateCallableWithArg(final String input) {
return () -> {
Thread.sleep(5000); // someExpensiveOperationHere
return "Return Value of " + input; //input can be used here
};
}
此外,我们可以编写一个静态辅助方法,可以将 Function 转换为 Callable。
public class CallableGenerator {
public static <T,V> Callable<V> getCallableFromFunction(Function<T, V> function, T input) {
return () -> function.apply(input);
}
}
这可以用作
Callable<Integer> iAmCallable = CallableGenerator.getCallableFromFunction(i1 -> i1 * 2, 3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.