方法的參數名,在不少時候咱們是須要反射獲得的。可是在java8以前,代碼編譯爲class文件後,方法參數的類型是固定的,但參數名稱卻丟失了,這和動態語言嚴重依賴參數名稱造成了鮮明對比。(java是靜態語言,因此入參名稱叫什麼其實無所謂的)。java
雖然名稱無所謂,但不少時候,咱們須要此名稱來作更好的安排,好比Myabtis的應用。下面介紹兩種方式獲取參數名:spring
1、經過jdk原生反射機制獲取 spa
import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.List; public class ParameterNameUtil { public static void main(String[] args) { List<String> paramterNames = getParameterNameJava8( ParameterNameUtil.class, "getParameterNameJava8"); paramterNames.forEach((x) -> System.out.println(x)); } public static List<String> getParameterNameJava8(Class clazz, String methodName) { List<String> paramterList = new ArrayList<>(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (methodName.equals(method.getName())) { //直接經過method就能拿到全部的參數 Parameter[] params = method.getParameters(); for (Parameter parameter : params) { paramterList.add(parameter.getName()); } } } return paramterList; } }
Java 8開始增長了類Parameter,在class文件中保留參數名,給反射帶來了極大的便利。代理
2、經過spring的LocalVariableTableParameterNameDiscoverer獲取調試
public static void main(String[] args) { List<String> paramterNames = getParamterName(ParameterNameUtil.class, "getParamterName"); paramterNames.forEach((x) -> System.out.println(x)); } public static List<String> getParamterName(Class clazz, String methodName) { LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (methodName.equals(method.getName())) { //獲取到該方法的參數們 String[] params = u.getParameterNames(method); return Arrays.asList(params); } } return null; }
備註:若是不用Class,而是經過spring注入的實例,而後instance.getClass.getDeclaredMethods()則沒法獲得參數名,調試時看到方法名稱是經過jdk代理過的,拿不到參數名。code
另外,能成功獲取方法參數的名稱須要知足兩個條件:blog
IDEA配置方法以下:get