Java 功能篇之 Object 转Map

工具类源码:

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MapTransPojo {
public static final Logger log = LoggerFactory.getLogger(MapTransPojo.class);
	
	public static Map<String,Object> PojoTransMap(Object obj){
		 Map<String, Object> map = new HashMap<String, Object>();
		 if (obj == null) {
			 return map;
		 }
		 // 获取当前类属性
		 Class clazz = obj.getClass();
		 Field[] fields = clazz.getDeclaredFields();
		 try {
			 for (Field field : fields) {
				 field.setAccessible(true);
				 if(field.get(obj) != null){
					 map.put(field.getName(), field.get(obj));					 
				 }
			 }
		 } catch (Exception e) {
			 log.error("MapTransPojo init error", e);
		 }	
		return map;
	}
	
	public static Map<String,Object> PojoTransMapSimple(Object obj){
		 Map<String, Object> map = new HashMap<String, Object>();
		 if (obj == null) {
			 return map;
		 }
		 Class clazz = obj.getClass();
		 Field[] fields = clazz.getDeclaredFields();
		 
		 try {
			 for (Field field : fields) {
				 field.setAccessible(true);
				 if(field.get(obj) != null){
					 map.put(field.getName(), SimpleTypeConverterUtil.convertIfNecessary(field.get(obj), field.getType()));
				 }
			 }
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
		return map;
	}

/**
	 * Map转实体类
	 * @param map 需要初始化的数据,key字段必须与实体类的成员名字一样,否则赋值为空
	 * @param entity  需要转化成的实体类
	 * @return
	 */
	public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
		T t = null;
		try {
			t = entity.newInstance();
			for(Field field : entity.getDeclaredFields()) {
				if (map.containsKey(field.getName())) {
					boolean flag = field.isAccessible();
		            field.setAccessible(true);
		            Object object = map.get(field.getName());
		            if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
		            	 field.set(t, object);
					}
		            field.setAccessible(flag);
				}
			}
			return t;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}

}

猜你喜欢

转载自blog.csdn.net/zhouzhiwengang/article/details/114144111