package com.blueland.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtil {
	/**
	 * javaBean 转 Map
	 * @param object object需要转换的javabean
	 * @return 转换结果map
	 * @throws Exception
	 */
	public static Map<String, Object> beanToMap(Object object) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Class cls = object.getClass();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			map.put(field.getName(), field.get(object));
		}
		return map;
	}

	/**
	 *
	 * @param map	需要转换的map
	 * @param cls	目标javaBean的类对象
	 * @return 		目标类object
	 * @throws 		Exception
	 */
	public static Object mapToBean(Map<String, Object> map, Class cls) throws Exception {
		Object object = cls.newInstance();
		for (String key : map.keySet()) {
			Field temFiels = cls.getDeclaredField(key);
			temFiels.setAccessible(true);
			temFiels.set(object, map.get(key));
		}
		return object;
	}

	/**
	 * 将一个map组成的list转成实体类bean组成的list
	 * @param mapList 存了map对象的list
	 * @param clazz 需要将这些map转成哪个实体类对象
	 * @return
	 */
	public static <T> List<T> convertMapListToBeanList(List<Map> mapList, Class<T> clazz){
		List<T> list=new ArrayList<T>();
		for(Map map:mapList){
			try {
				T obj=clazz.newInstance();//创建bean的实例对象
				for(Object o:map.keySet()){//遍历map的key
					for(Method m:clazz.getMethods()){//遍历bean的类中的方法，找到set方法进行赋值
						if(m.getName().toLowerCase().equals("set"+o.toString().toLowerCase())){
							if(o.toString().indexOf("Time") != -1){
								continue;
							}else{
								m.invoke(obj, map.get(o));
							}
						}
					}
				}
				list.add(obj);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

}
