Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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