public static Object callMethod(final Object target , final String methodName ,final Class<?>[] parameterTypes,final Object[]params) throws Exception{
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) {
e.printStackTrace() ;
throw e ;
}
return value ;
}
});
executorService.execute(future);
String result = null;
try{
/**获取方法返回值 并设定方法执行的时间为30秒*/
result = future.get(30 , TimeUnit.SECONDS );
}catch (InterruptedException e) {
future.cancel(true);
System.out.println("方法执行中断");
}catch (ExecutionException e) {
future.cancel(true);
System.out.println("Excuti on异常");
}catch (TimeoutException e) {
future.cancel(true);
throw new RuntimeException("invoke timeout" , e );
}
executorService.shutdownNow();
return result ;
}