版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Z201220122012/article/details/79726042
javaBean中含有枚举类型属性的自动封装
近日做项目的时候,依旧被超长表单困扰,所以学习了一下自动封装
写了一个PropertyDescriptor
类实现的自动封装方法,然而对于属性中有枚举类型的
很是难受,因为从request
中获取的Map集合是Map <String, String[]>
的
开始想的是重载一个set方法,然而PropertyDescriptor的getWriteMethod方法
只能获取参数类型与属性的类型相同的方法,所以我写的重载方法获取不到。。。
于是自己动手写了一个
这个是通过servlet的request中获取的Map来实现对象自动封装
将javaBean类的参数类型为枚举类型的set方法删掉,然后写一个参数类型为String的方法
public void setB_sex(String b_sex) {
this.b_sex = Sex.valueOf(b_sex);
}
然后是自动封装方法的实现
@SuppressWarnings("rawtypes")
public static Object getBean(HttpServletRequest request, Class type) {
try {
Map<String, String[]> map = request.getParameterMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
Object obj = type.newInstance();
PropertyDescriptor[] propretyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : propretyDescriptors) {
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
String[] value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value[0];
// System.out.println(propertyName);
// try {
// System.out.println(descriptor.getWriteMethod().getName());
// } catch (NullPointerException e) {
// System.out.println(propertyName + "的WriteMethod未找到");
// }
Method m = descriptor.getWriteMethod();
if (m != null) {
m.invoke(obj, args);
} else {
String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
@SuppressWarnings("unchecked")
Method setMethod = type.getMethod(setMethodName, String.class);
setMethod.invoke(obj, args);
}
}
}
return obj;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
System.out.println("未找到方法参数为String的方法");
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return null;
}