java的反射是不能获取方法的参数名的。比如:
[java] view plaincopyprint?
- public String concatString(String str1,String str2){
- return str1+str2;
- }
public String concatString(String str1,String str2){ return str1+str2; }
想获取"str1",和"str1"这个参数名,使用JDK自带的反射是不行的。但是我们借助第三方包
javaassist
就可以获得。
[java] view plaincopyprint?
- public static void main(String[] args) {
- Class clazz = TestJavaAssist.class;
- try {
- ClassPool pool = ClassPool.getDefault();
- CtClass cc = pool.get(clazz.getName());
- CtMethod cm = cc.getDeclaredMethod("concatString");
- // 使用javaassist的反射方法获取方法的参数名
- MethodInfo methodInfo = cm.getMethodInfo();
- CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
- LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
- if (attr == null) {
- // exception
- }
- String[] paramNames = new String[cm.getParameterTypes().length];
- int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
- for (int i = 0; i < paramNames.length; i++)
- paramNames[i] = attr.variableName(i + pos);
- // paramNames即参数名
- for (int i = 0; i < paramNames.length; i++) {
- System.out.println(paramNames[i]);
- }
- } catch (NotFoundException e) {
- e.printStackTrace();
- }
- }
public static void main(String[] args) { Class clazz = TestJavaAssist.class; try { ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get(clazz.getName()); CtMethod cm = cc.getDeclaredMethod("concatString"); // 使用javaassist的反射方法获取方法的参数名 MethodInfo methodInfo = cm.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag); if (attr == null) { // exception } String[] paramNames = new String[cm.getParameterTypes().length]; int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < paramNames.length; i++) paramNames[i] = attr.variableName(i + pos); // paramNames即参数名 for (int i = 0; i < paramNames.length; i++) { System.out.println(paramNames[i]); } } catch (NotFoundException e) { e.printStackTrace(); } }
时间: 2024-11-08 14:31:10