public static Object callMethod(final Object target , final String methodName ,final Class[] parameterTypes,final Object[]params,int times){
ExecutorService executorService = Executors.newSingleThreadExecutor();
FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
public String call() throws Exception {
String value = null ;
try {
Method method = null ;
method = target.getClass().getDeclaredMethod(methodName , parameterTypes ) ;
Object returnValue = method.invoke(target, params) ;
value = returnValue != null ? returnValue.toString() : null ;
} catch (Exception e) {
throw e ;
}
return value ;
}
});
executorService.execute(future);
String result = null;
try{
result = future.get(times , TimeUnit.SECONDS );
}catch (Exception e){
System.out.println("当前终端无法连接");
e.printStackTrace();
}
executorService.shutdownNow();
return result ;
}
这段代码 是我在网上找的可以控制等待时间运行方法的代码 可如果要运行的方法有返回值的话 我该怎么接收呢
返回值会作为 String 类型被存储在 result 变量中。你可以通过打印出来或者将其存储在其他变量中,然后进一步使用它。例如:
String result = (String) callMethod(...);
System.out.println(result);
如果要接收方法的返回值,可以将其存储到一个变量中。例如,在上面的代码中,您可以将返回值存储在“result”变量中,然后在future.get(times, TimeUnit.SECONDS)之后即可拿到该返回值。
该回答引用ChatGPT
段代码中,方法调用结果存储在String类型的变量"result"中,接收的方式如下
String result = (String) callMethod(target, methodName, parameterTypes, params, times);
在使用时,需要确保运行的方法的返回值是可以转换成String类型的。如果不是,可以将代码中的String类型修改为方法的返回值的类型,并在接收结果时对应修改。
如果方法有返回值,你可以在代码的最后,将结果作为Object类型返回,然后在调用的地方通过类型转换获取实际的返回值类型。
例如,如果方法的返回值是一个整数,则可以这样获取:
int result = (Integer) callMethod(target, methodName, parameterTypes, params, times);
不知道你这个问题是否已经解决, 如果还没有解决的话: