1. 程式人生 > >java反射獲取字段的屬性值,以及為字段賦值等方法

java反射獲取字段的屬性值,以及為字段賦值等方法

通過 獲取 首字母 color als 遍歷 方法 access col

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;

java反射獲取字段的屬性值,以及為字段賦值等方法