本文给出两个函数:
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);
}
}
注:上面两个函数,也只是练习了一下自己对java反射的应用。在真实的项目开发过程中,我一般还是用commons-beanutils.jar包。
其中提供了类似PropertyUtils和BeanUtils的工具类。