java 输入方法名和参数,就可以得到结果

通过获取一个类中的所有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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值