java反射-BeanUtils.getFieldValue(object,property)
Posted on 2012-04-15 16:37 zljpp 閱讀(470) 評論(0) 編輯 收藏本文給出兩個函數:
BeanUtils.getFieldValue(object,propertyName);//取出object對象中的propertyName屬性的值.propertyName只能是object所在類中定義的,而不是其基類定義的
BeanUtils.getFieldValueInAllSuper(object,propertyName);//);//取出object對象中的propertyName屬性的值.propertyName包括在object所在類的基類中定義的屬性
看代碼:
- public class BeanUtils {
- /**
- * 獲取當前類聲明的private/protected變量
- */
- 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);
- }
- /**
- * zhangpf :因為getFieldValue()方法,無法讀取super class的屬性的值;
- * 所以本方法做出擴展,允許讀取super class的屬性的值;
- * @param object
- * @param propertyName
- * @return
- * @throws IllegalAccessException
- * @throws NoSuchFieldException
- */
- 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)
- {
- //e.printStackTrace();
- field=null;
- }
- claszz=claszz.getSuperclass();
- }
- while(field==null&&claszz!=null);
- if(field==null) return null;
- field.setAccessible(true);
- return field.get(object);
- }
- }