Posted on 2012-04-15 16:37
zljpp 阅读(469)
评论(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);
- }
- }