/** * map转对象 * @param map * @param beanClass * @return * @throws Exception */ public static Object mapToObject(Map<String, Object> map,Class<?> beanClass) throws Exception { Object obj = beanClass.newInstance(); if (map == null){ obj=null; }else { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { Method setter = property.getWriteMethod(); if (setter != null) { setter.invoke(obj, map.get(property.getName())); } } } return obj; } /** * 对象转map * @param obj * @return * @throws Exception */ public static Map<String, Object> objectToMap(Object obj) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if(obj == null){ map=null; }else { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (key.compareToIgnoreCase("class") == 0) { continue; } Method getter = property.getReadMethod(); Object value = getter!=null ? getter.invoke(obj) : null; map.put(key, value); } } return map; }
java对象与map对象相互转换
最新推荐文章于 2023-12-10 09:00:00 发布