/**
* 通过javabean调用对象的set方法
*
* @param object
* @param propertyName
* @param propertyValue
* @Author zy
*/
public static void setPropertyValue(Object object, String propertyName, Object propertyValue) throws Exception {
if (object == null)
throw new Exception("object 参数不能为空!");
if (propertyName == null)
throw new Exception("propertyName 参数不能为空!");
try {
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (propertyName.equals(propertyDescriptor.getName())) {
if (propertyDescriptor.getPropertyType() == null ||
!propertyDescriptor.getPropertyType().equals(propertyValue.getClass())) {
throw new Exception("propertyValue 类型不匹配");
}
propertyDescriptor.getWriteMethod().invoke(object, propertyValue);
break;
}
}
} catch (Exception e) {
throw e;
}
}
网友评论