我想知道一个方法的参数个数,它给出了Chapter 4 The class file Format - Section 4.3.3中指定的方法描述符。是否有提供此实用程序的内置函数?
答案 0 :(得分:3)
我不知道内置方法,但偶尔也会实现一个。
private static Pattern allParamsPattern = Pattern.compile("(\\(.*?\\))");
private static Pattern paramsPattern = Pattern.compile("(\\[?)(C|Z|S|I|J|F|D|(:?L[^;]+;))");
int getMethodParamCount(String methodRefType) {
Matcher m = allParamsPattern.matcher(methodRefType);
if (!m.find()) {
throw new IllegalArgumentException("Method signature does not contain parameters");
}
String paramsDescriptor = m.group(1);
Matcher mParam = paramsPattern.matcher(paramsDescriptor);
int count = 0;
while (mParam.find()) {
count++;
}
return count;
}
欢迎您参考完整的源代码here。
答案 1 :(得分:0)
看看这是否有效...我也在使用ASM,这是我编制的方法......现在已经使用了一段时间......
public static int getMethodArgumentCount(String desc) {
int beginIndex = desc.indexOf('(') + 1;
int endIndex = desc.lastIndexOf(')');
String x0 = desc.substring(beginIndex, endIndex);//Extract the part related to the arguments
String x1 = x0.replace("[", "");//remove the [ symbols for arrays to avoid confusion.
String x2 = x1.replace(";", "; ");//add an extra space after each semicolon.
String x3 = x2.replaceAll("L\\S+;", "L");//replace all the substrings starting with L, ending with ; and containing non whitespace characters inbetween with L.
String x4 = x3.replace(" ", "");//remove the previously inserted spaces.
return x4.length();//count the number of elements left.
}
答案 2 :(得分:-1)
方法#getParameterTypes()。length?
答案 3 :(得分:-1)
您可以使用method.getParameterTypes()
。它为您提供了一系列参数类型,因此您可以知道有多少参数。