JavaBean和Map相互转换

package com.bootdo.common.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Bean2MapUtil {
	public static void Map2Bean(Map<String, Object> map, Object obj) {
		       if (map == null || obj == null) {
		           return;
		       }
		        try {
		            BeanUtils.populate(obj, map);
		       } catch (Exception e) {
		     }
		    }

	public static Map<String, Object> Bean2Map(Object obj) {

		if(obj == null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				if (!key.equals("class")) {
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					map.put(key, value);
				}

			}
		} catch (Exception e) {
		}

		return map;

	}
}

猜你喜欢

转载自blog.csdn.net/weixin_39270764/article/details/80008778