package com.qmth.themis.common.util;

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

public class SimpleBeanUtil {
	public static Map<String, Object> objectToMap(Object obj) {
		if (obj == null) {
			throw new RuntimeException("Object is null");
		}
		// 获取关联的所有类，本类以及所有父类
		boolean ret = true;
		Class oo = obj.getClass();
		List<Class> clazzs = new ArrayList<Class>();
		while (ret) {
			clazzs.add(oo);
			oo = oo.getSuperclass();
			if (oo == null || oo == Object.class) {
				break;
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();

		for (int i = 0; i < clazzs.size(); i++) {
			Field[] declaredFields = clazzs.get(i).getDeclaredFields();
			for (Field field : declaredFields) {
				int mod = field.getModifiers();
				// 过滤 static 和 final 类型
				if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
					continue;
				}
				field.setAccessible(true);
				try {
					map.put(field.getName(), field.get(obj));
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}

		return map;
	}

	public static  <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
		if (map == null) {
			return null;
		}
		try {
			T obj = beanClass.newInstance();

			Field[] fields = obj.getClass().getDeclaredFields();
			for (Field field : fields) {
				int mod = field.getModifiers();
				if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
					continue;
				}

				field.setAccessible(true);
				field.set(obj, map.get(field.getName()));
			}
			return obj;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
