通过class.getFields()方法获得类的所有公共属性。
如果该类或接口不声明任何字段,或者此 Class
对象表示一个基本类型、一个数组类或 void,则此方法返回一个长度为 0 的数组。

1 import lombok.Data; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 * 测试的实体类 6 * @Data 编译后会自动生成set、get、无惨构造、equals、canEqual、hashCode、toString方法 7 */ 8 @Data 9 public class Person { 10 private String name; 11 private int age; 12 public String nickName; 13 14 }

1 import java.lang.reflect.Field; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 */ 6 public class NewInstanceTest { 7 public static void main(String[] args) { 8 Class<Person> personClass = Person.class; 9 try { 10 Field[] fields = personClass.getFields(); 11 for (Field f : fields) { 12 System.out.println(f); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 } 18 }
通过class.getDeclaredFields()方法获得类的所有属性(公共,保护,默认,和私有属性)。
如果该类或接口不声明任何字段,或者此 Class
对象表示一个基本类型、一个数组类或 void,则此方法返回一个长度为 0 的数组。

1 import java.lang.reflect.Field; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 */ 6 public class NewInstanceTest { 7 public static void main(String[] args) { 8 Class<Person> personClass = Person.class; 9 try { 10 Field[] fields = personClass.getDeclaredFields(); 11 for (Field f : fields) { 12 System.out.println(f); 13 } 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 } 18 }
注意:返回的方法数组中的元素没有排序,也没有任何特定的顺序。
获得属性之后修改这个属性,特别注意私有属性:

1 import java.lang.reflect.Field; 2 3 /** 4 * Created by hunt on 2017/6/27. 5 */ 6 public class NewInstanceTest { 7 public static void main(String[] args) { 8 Class<Person> personClass = Person.class; 9 try { 10 Person p = personClass.newInstance(); 11 Field field = personClass.getDeclaredField("name"); 12 field.setAccessible(true);//私有属性更改要授权 13 field.set(p,"私有hunt"); 14 field = personClass.getDeclaredField("nickName"); 15 field.set(p,"共有hunt"); 16 System.out.println(p); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 } 20 } 21 }
总结:field.setAccessible(
true
);
基于对属性的保护,默认为false。这里相当于一个授权的过程,设置true来允许操作这个属性。