关于最基础的JAVA反射问题
来源:百度知道 编辑:UC知道 时间:2024/06/25 22:15:04
public class Students {
public String name;
public int age;
public int id;
private String sex;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
这个要用反射做什么?!
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class ValueSetter {
public static void initStudents(Students stu,String name, int age, int id,String sex) throws Exception {
PropertyDescriptor[] pds = Introspector.getBeanInfo(stu.getClass()).getPropertyDescriptors();
for(PropertyDescriptor pd : pds) {
Method method = pd.getWriteMethod();
String proName = pd.getName();
if(proName.equals("name")) {
method.invoke(stu, name);
} else if (proName.equals("age")) {
method.invoke(stu, age);
} else if (proName.equals("id")) {
method.invoke(stu, id);
} else if (proName.equals("sex")) {
method.invoke(stu, sex);
}
}
}
public static void main(String[] args) throws Exception {
Students stu = new Students();