通过获取一个类中的所有public方法,只用输入方法名就能得到运行结果。
/**
* 遍历运行某类中的public方法并返回String结果
* @param name 方法名 "Forecast15Days"
* @param params 默认这个方法的输入参数都是一样的
* @return 该方法返回的原始数据
*/
public String GetApiValue(String name, String[] params)throws Exception{
AliWeatherService weatherService = new AliWeatherService();
DataProcessUtil dp = new DataProcessUtil();
// 获取所有的方法名字
String[] names = dp.GetMethod(Class.forName("com.bingqi.service.AliWeatherService"));
Map<String, String[]> methods = new HashMap<>();
assert params != null;
if (name != null & params.length==2 & Arrays.asList(names).contains(name)){
methods.put(name, params);
for (Map.Entry<String, String[]> item : methods.entrySet()) {
try {
//getMethod第一个参数是函数名,后面的参数都是针对于目标方法的参数类型,没有参数就传null
Method method = AliWeatherService.class.getMethod(item.getKey(), String[].class);
//invoke第一个参数是一个对象的实例,后面跟进一堆参数列表,没有参数就传null
return (String)method.invoke(weatherService, (Object) item.getValue());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
return "";
}
/**
* 获取一个类的所有public方法
* @param type 类型
* @return names 方法名的String数组
*/
public String[] GetMethod(Class type) throws Exception {
Method[] methods = type.getDeclaredMethods();//取得该类的所有方法
String[] names = new String[methods.length];
for (int i=0; i<methods.length; i++) {
String method_name = methods[i].getName();//取得该方法的名
names[i] = method_name;
}
return names;
}