java反射获取字段的属性值,以及为字段赋值等方法

1.获取某个类的属性值

1 /*利用getter方法获取值(首字母大写)
2 CjJssetDTO obj;
3 */
4                     String filedName = "Cj"+(i+1);
5                      
6                      Class<?> cl = obj.getClass();  
7                         Method me = cl.getDeclaredMethod("get"+filedName);  
8                         
9                        String value = (String) me.invoke(obj) ; 

在CjJssetDTO中,有名为cj1,cj2...的字段。由于列不固定,所以获取值的时候,需要使用反射。通过循环遍历,取到cj1,cj2等字段的值。

2.设置某个属性的值

1  /**set值*/
2                        String filedName1 = "cj"+(i+1);
3                        Field name = xs.getClass().getDeclaredField(filedName1+"");  
4                         name.setAccessible(true);   
5                         name.set(xs,Double.valueOf(value));  
6                         name.setAccessible(false);  

通过循环遍历,设置cj1,cj2等字段的值。

其中, Field是java.lang.reflect.Field;

Method是 java.lang.reflect.Method;
原文地址:https://www.cnblogs.com/ws5167/p/7667505.html