在使用Oracle数据库时经常出现数据库char字段被空字符填充的情况,在写业务代码时需要对字段进行处理,BeanHelper.beanAttributeValueTrim(object);
public class BeanHelper {public static void beanAttributeValueTrim(Object bean) throws Exception {if (bean != null){Field[] fields = bean.getClass().getDeclaredFields();for (int i = 0; i < fields.length; i++) {Field f = fields[i];if (f.getType().getName().equals("java.lang.String")) {String key = f.getName();Object value = getFieldValue(bean, key);if (value == null)continue;setFieldValue(bean, key, value.toString().trim());}}}}private static Object getFieldValue(Object bean, String fieldName) throws Exception{StringBuffer result = new StringBuffer();String methodName = result.append("get").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString();Object rObject = null;Method method = null;Class[] classArr = new Class[0];method = bean.getClass().getMethod(methodName, classArr);rObject = method.invoke(bean, new Object[0]);return rObject;}private static void setFieldValue(Object bean, String fieldName, Object value) throws Exception{StringBuffer result = new StringBuffer();String methodName = result.append("set").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString();Class[] classArr = new Class[1];classArr[0] = "java.lang.String".getClass();Method method = bean.getClass().getMethod(methodName, classArr);method.invoke(bean, value);}
}