反射getDeclaredFields()

public static void main(String[] args) {
// 获取所有属性值
Field[] fields = People.class.getDeclaredFields();
for (Field field : fields) {
// 要拿到属性值必须设置为true
field.setAccessible(true);
System.out.println("属性名称:" + field.getName());
try {
System.out.println("属性值:" + field.get(new People()).toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

 

 

public class People {
private String name="jinxudong";
private String sex="nan";
public String address="北京市";
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

posted @ 2018-05-22 15:22  洞玄巅峰  阅读(256)  评论(0编辑  收藏  举报