Skip to content

Instantly share code, notes, and snippets.

@JeasonWong
Last active September 7, 2018 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeasonWong/abd4584199652bde76a988236c619ebe to your computer and use it in GitHub Desktop.
Save JeasonWong/abd4584199652bde76a988236c619ebe to your computer and use it in GitHub Desktop.
javassist-getParamtersName
/**
* 获取方法参数名称
*/
@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