使用内省的方式操作JavaBean
Sun公司提供了工具类>BeanUtils工具类操作JavaBean(commons-beanUtils-current.zip)
传递的过程中通过字符串传递
或者通过Java工具类PropertyUtils操作JavaBean
传递的过程中通过字段本身类型进行传递
下面的代码写起来太麻烦,了解一下就够了。
/**
* 获得对象的属性值
* @param obj 属性所属的对象
* @param propertyName 属性名
* @return 属性的值
*/
private static Object getProperty(Object obj, String propertyName) throws Exception {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,obj.getClass());
Method getMethod = pd.getReadMethod(); //获得get方法
Object retVal = getMethod.invoke(obj);
return retVal;
}
/**
* 设置属性的值
* @param obj 属性所属的对象
* @param propertyName 属性名
* @param propertyValue 属性值
*/
private static void setProperty(Object obj, String propertyName,Object propertyValue) throws Exception {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,obj.getClass());
Method setMethod = pd2.getWriteMethod();
setMethod.invoke(obj, propertyValue);
}
/**
* 使用内省操作javabean
* @param obj 属性所属的对象
* @param propertyName 属性名
* @return 属性的值
*/
private static Object getProperty2(Object obj, String propertyName) throws Exception {
Object retVal = null;
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals(propertyName)) {
Method getMethod = pd.getReadMethod();
retVal = getMethod.invoke(obj);
break;
}
}
return retVal;
}
}