1. Java8
public class TestGetMethodParamName {
public String test(String name, Integer age) {
return null;
}
public static String printMethods() {
StringBuilder sb = new StringBuilder();
for (Method m : TestGetMethodParamName.class.getDeclaredMethods()) {
sb.append(m.getReturnType().getSimpleName());
sb.append(" ").append(m.getName());
sb.append("(");
String paramString = Stream.of(m.getParameters())
.map(p -> p.getType().getSimpleName() + " " + p.getName())
.collect(Collectors.joining(", "));
sb.append(paramString);
sb.append(")\n");
}
return sb.toString();
}
public static void main(String args[]) {
String s = printMethods();
System.out.println(s);
}
}
执行结果:
void main(String[] arg0)
String test(String arg0, Integer arg1)
String lambda$0(Parameter arg0)
String printMethods()
- 设置下Eclipse
再次执行
void main(String[] args)
String test(String name, Integer age)
String lambda$0(Parameter p)
String printMethods()
用javac命令的时候增加 -parameters参数即可
-parameters 生成元数据以用于方法参数的反射
java com/cctv/website/core/common/extension/reflect/TestGetMethodParamName
void main(String[] arg0)
String test(String arg0, Integer arg1)
String printMethods()
String lambda$printMethods$0(Parameter arg0)
localhost:java bao$ javac -parameters com/cctv/website/core/common/extension/reflect/TestGetMethodParamName2.java
localhost:java bao$ java com/cctv/website/core/common/extension/reflect/TestGetMethodParamName2
void main(String[] args)
String test(String nameInteger age)
String printMethods()
注:IDEA的设置如下
preferences->