利用java内省机制封装实用工具一

来源:互联网 发布:淘宝代刷兼职 编辑:程序博客网 时间:2024/06/02 01:46

为了方便将表单提交上来的参数和map集合中的数据快速封装成对象,利用java的内省机制编写该方法。话不多说直接上代码。

public class BeanUtils {private BeanUtils() {}/** * @Description  将map集合中的值装入实体对象 * @param bean  实体对象 * @param map  值 * @throws Exception */public static void populate(Object bean, Map<String, ?> map) throws Exception {BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();for (PropertyDescriptor property : descriptors) {String name = property.getName();Method method2 = property.getWriteMethod();Object object = map.get(name);if (object instanceof String[]) {  //表单提交上来的请求参数  value 值数组类型所以转换 取第一个值String[] string = (String[]) object;String value = string[0];change(bean, property, method2, value);} else {change(bean, property, method2, object + "");}}}private static void change(Object bean, PropertyDescriptor property, Method method2, String value)throws IllegalAccessException, InvocationTargetException, ParseException {//取出字段属性Class<?> type = property.getPropertyType();String typename = type.getName();switch (typename) {case "java.lang.String":method2.invoke(bean, value + "");break;case "java.lang.Integer":method2.invoke(bean, Integer.parseInt(value + ""));break;case "java.lang.Double":method2.invoke(bean, Double.parseDouble(value + ""));break;case "java.lang.Float":method2.invoke(bean, Double.parseDouble(value + ""));break;case "java.util.Date":SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");Date date = null;try {date = format.parse(value + "");} catch (ParseException e) {date = format2.parse(value + "");}method2.invoke(bean, date);break;}}}




原创粉丝点击