Posted on 2012-04-15 16:37
zljpp 閱讀(473)
評論(0) 編輯 收藏
本文給出兩個函數:
BeanUtils.getFieldValue(object,propertyName);//取出object對象中的propertyName屬性的值.propertyName只能是object所在類中定義的,而不是其基類定義的
BeanUtils.getFieldValueInAllSuper(object,propertyName);//);//取出object對象中的propertyName屬性的值.propertyName包括在object所在類的基類中定義的屬性
看代碼:
- public class BeanUtils {
-
-
-
-
-
- static public Object getFieldValue(Object object, String propertyName)
- throws IllegalAccessException, NoSuchFieldException {
- Assert.notNull(object);
- Assert.hasText(propertyName);
- Field field = object.getClass().getDeclaredField(propertyName);
- field.setAccessible(true);
-
- return field.get(object);
- }
-
-
-
-
-
-
-
-
-
- public static Object getFieldValueInAllSuper(Object object, String propertyName)
- throws IllegalAccessException, NoSuchFieldException {
- Assert.notNull(object);
- Assert.hasText(propertyName);
- Class claszz=object.getClass();
- Field field = null;
-
- do
- {
- try{
- field = claszz.getDeclaredField(propertyName);
- }
- catch(NoSuchFieldException e)
- {
-
- field=null;
- }
- claszz=claszz.getSuperclass();
- }
- while(field==null&&claszz!=null);
-
- if(field==null) return null;
-
- field.setAccessible(true);
- return field.get(object);
- }
- }