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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM