从 Java 1.8 开始,只要参数名称在类文件中,就可以做到这一点。使用javac
它是通过传递-parameters
标志完成的。从javac
帮助
-parameters Generate metadata for reflection on method parameters
在 IDE 中,您需要查看编译器设置。
如果参数名称在类文件中,那么这里是一个这样做的例子
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class ParameterNamesExamples {
public static void main(String[] args) throws Exception {
Method theDoSomethingMethod = ExampleClass.class.getMethods()[0];
// Now loop through the parameters printing the names
for(Parameter parameter : theDoSomethingMethod.getParameters()) {
System.out.println(parameter.getName());
}
}
private class ExampleClass {
public void doSomething(String myFirstParameter, String mySecondParameter) {
// No-op
}
}
}
输出将取决于参数名称是否在类文件中。如果它们是输出是:
myFirstParameter
mySecondParameter
如果不是,则输出为:
arg0
arg1
可以在获取方法参数的名称中找到来自 Oracle 的更多信息