获得一个类的属性

通过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 }
View Code
 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 }
View Code

通过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 }
View Code

 

注意:返回的方法数组中的元素没有排序,也没有任何特定的顺序。

获得属性之后修改这个属性,特别注意私有属性:

 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 }
View Code

总结:field.setAccessible(true);

基于对属性的保护,默认为false。这里相当于一个授权的过程,设置true来允许操作这个属性。

 

转载于:https://www.cnblogs.com/hunt/p/7095390.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值