1. 程式人生 > >java 通過反射獲取方法引數列表名稱

java 通過反射獲取方法引數列表名稱

說明

            一般情況下是使用不到用反射來獲取引數列表名稱的,只要知道引數列表的型別就可以執行某一個引數了,因為引數名稱是給開發人員用的,執行時引數名稱不起作用。

所以 JDK 本身是沒有獲取引數列表名稱的。

         如果要寫框架一類的東西,比如前些日子我們有個平臺需要用到MVC框架,但裡邊不支援Spring MVC 只能模仿Spring寫一個框架, 在前臺像後臺封裝引數的時候,因為需

要前臺引數和後臺方法的引數根據名稱封裝,所以就需要獲取引數列表每個引數名稱。

需要的jar包

javassist-3.9.0.GA.jar

程式碼

 ClassPool pool = ClassPool.getDefault();
  
  CtClass cc;
  
  try {
   cc = pool.get(DispatchUriUtils.class.getName());
   
   CtMethod cm = cc.getDeclaredMethod("findAndAddClassesInPackageByFile");
   
   MethodInfo info = cm.getMethodInfo();
   
   CodeAttribute codeAttribute = info.getCodeAttribute();
   
   LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);

   int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;

   String[] names=new String[cm.getParameterTypes().length];
   
   for (int i = 0; i < names.length; i++)
   {
    names[i] = attr.variableName(i + pos);
    
    System.out.println(names[i]);
   }
   
  } catch (NotFoundException e) {
   e.printStackTrace();
  }

結果

packageName
packagePath
recursive
classes