public class TestReflect {
public static void main(String[] args){ APerson a=new APerson(); Field fields[] = a.getClass().getDeclaredFields(); String[] name = new String[fields.length]; Object[] value = new Object[fields.length]; try{ Field.setAccessible(fields, true); for (int i = 0; i < name.length; i++) { name[i] = fields[i].getName(); System.out.println(name[i] + "-> "); value[i] = fields[i].get(a); System.out.println(value[i]); } } catch(Exception e){ e.printStackTrace(); } } } class APerson{ private String name; private String sex; private int age; APerson(){ name= "John "; sex= "男 "; age=45; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } 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; } }以上代码中,Field.setAccessible(fields, true); 是最为关键的一点。
在使用java反射机制获取 JavaBean 的属性值时,如果该属性被声明为private 的,需要将setAccessible设置为true. 默认的值为false.