使用spring的LocalVariableTableParameterNameDiscoverer获取类方法参数名称列表

package com.yanek.soa.test;

import java.lang.reflect.Method;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

public class MethodParmsVariableNameUtil {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		
		String[] names=getMethodParams("com.yanek.soa.test.Test","test2");
		for(String name:names){

			System.out.println(name);
		}
	}
	

	/**
     * 获取方法所有参数名
     * @param method
     * @return
     */
    public static String[] getParameterNames(Method method) {
        return parameterNameDiscoverer.getParameterNames(method);
    }
	
    private static final LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
	
	public static String[] getMethodParams(String className, String methodName) throws ClassNotFoundException {
        Class<?> aClass = Class.forName(className);
        Method[] methods = aClass.getMethods();
        String[] params = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                params = getParameterNames(method);
                if (params == null || params.length == 0) {
                    break;
                }
                StringBuilder sb = new StringBuilder();
                sb.append("方法:" + method.getName() + "()  ");
                for (int i = 0; i < params.length; i++) {
                    if (i > 0) {
                        sb.append(" ,");
                    }
                    sb.append(params[i]);
                }
                System.out.println(sb.toString());
                break;
            }
        }
        return params;
    }

	

}
package com.yanek.soa.test;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	

	}
	
	
    public  String test(String a,String b,User user) {
        return "hello";
    }
    
    public static String test2(String a,String b,User user) {
        return "hello";
    }

    public static String test3(String p1,String p2,User user) {
        return "hello";
    }
    
    
}


©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值