java 对象转map,map转对象

来源:互联网 发布:mac os x 10.6 ios 编辑:程序博客网 时间:2024/05/08 15:31

java对象转map:

/** * JavaBean对象转化成Map对象 *  * @param javaBean * @return */@SuppressWarnings({ "rawtypes", "unchecked" })public static Map java2Map(Object javaBean) {Map map = new HashMap();try {// 获取javaBean属性BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();if (propertyDescriptors != null && propertyDescriptors.length > 0) {String propertyName = null; // javaBean属性名Object propertyValue = null; // javaBean属性值for (PropertyDescriptor pd : propertyDescriptors) {propertyName = pd.getName();if (!propertyName.equals("class")) {Method readMethod = pd.getReadMethod();propertyValue = readMethod.invoke(javaBean, new Object[0]);map.put(propertyName, propertyValue);}}}} catch (Exception e) {e.printStackTrace();}return map;}

map转java对象:

/** * map转换为对象 *  * @param clazz * @param map * @return */@SuppressWarnings("rawtypes")private static <T> T toBean(Class<T> clazz, Map map) {T obj = null;try {BeanInfo beanInfo = Introspector.getBeanInfo(clazz);obj = clazz.newInstance(); // 创建 JavaBean 对象// 给 JavaBean 对象的属性赋值PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (int i = 0; i < propertyDescriptors.length; i++) {PropertyDescriptor descriptor = propertyDescriptors[i];String propertyName = descriptor.getName();if (map.containsKey(propertyName)) {// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。Object value = map.get(propertyName);if ("".equals(value)) {value = null;}Object[] args = new Object[1];args[0] = value;try {descriptor.getWriteMethod().invoke(obj, args);} catch (InvocationTargetException e) {System.out.println("字段映射失败");}}}} catch (IllegalAccessException e) {System.out.println("实例化 JavaBean 失败");} catch (IntrospectionException e) {System.out.println("分析类属性失败");} catch (IllegalArgumentException e) {System.out.println(e.getMessage());System.out.println("映射错误");} catch (InstantiationException e) {System.out.println("实例化 JavaBean 失败");}return (T) obj;}


原创粉丝点击