Last active
September 7, 2018 10:11
-
-
Save JeasonWong/abd4584199652bde76a988236c619ebe to your computer and use it in GitHub Desktop.
javassist-getParamtersName
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取方法参数名称 | |
*/ | |
@Nullable | |
protected static String[] getMethodParamNames(CtMethod cm) { | |
String[] paramNames = null; | |
try { | |
MethodInfo methodInfo = cm.getMethodInfo(); | |
CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); | |
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute | |
.getAttribute(LocalVariableAttribute.tag); | |
if (attr == null) { | |
throw new RuntimeException("Method:" + cm.getLongName() | |
+ ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file"); | |
} | |
paramNames = new String[cm.getParameterTypes().length]; | |
TreeMap<Integer, Integer> map = new TreeMap<>(); | |
for (int i = 0; i < attr.tableLength(); i++) { | |
map.put(attr.index(i), i); | |
} | |
int index = 0; | |
boolean isStaticMethod = Modifier.isStatic(cm.getModifiers()); | |
boolean flag = false; | |
for (Integer key : map.keySet()) { | |
//如果是非静态方法,第0个attr.variableName(0)返回this,所以要跳过 | |
if (!isStaticMethod && !flag) { | |
flag = true; | |
continue; | |
} | |
if (index < paramNames.length) { | |
paramNames[index++] = attr.variableName(map.get(key)); | |
} else { | |
break; | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return paramNames; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment