场景
在某管理系统中需要对一月中的每天进行设置某个状态
对应的实体类的属性为
分别为d1 d2 一直到第31号。前端传递到后台的是d1 d2 d3等实体类对应的属性和要设置的状态的字段。
怎样将这些属性根据名字进行更新。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
可以通过JDK自带的反射下的getClass下的getDeclaredField并传递一个属性名字来获取该属性
Field field = kqbbKqybNew.getClass().getDeclaredField(shuxing);
获取属性对应值需要提前设置可访问
field.setAccessible(true); field.get(oldKqbbKqyb);
其中传递的参数是要获取其属性值的对象。
怎样设置其属性值
field.setAccessible(true); field.set(kqbbKqybNew, "公众号:霸道的程序猿");
其中第一个参数也是要设置其属性值的对象。
完整示例代码
设置
A a = new A(); Field field = a.getClass().getDeclaredField("x"); field.setAccessible(true); field.set(a, 1);
读取
Field f = a.getClass().getDeclaredField("x"); f.setAccessible(true); System.out.println(f.get(a));