在 JDK8 中增加了 Parameter 参数类,可以通过反射拿到方法的参数.
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
public class ParameterGet {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> studentClass = Class.forName("jdk8.test.Student");
Method[] methods = studentClass.getMethods();
for(Method method:methods) {
if(method.getName().startsWith("set")) {
System.out.println(method.getName());
Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
System.out.println(parameter.getName()+"----"+parameter.getType().getSimpleName());
}
}
}
}
}
执行main方法,输入为:
修改eclipse complier配置:
修改eclipse配置后 运行main方法:
原理是:编译的时候 加上 -parameters会把参数名也编译进去。