package com.lightinit.hsdataportal.common;

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

/**
 * Created by Mr.Yao on 2017/5/9.
 */
public class ObjectConvertorUtils<T> {

    public T DictToObject(Map<String, String> map,Class<T> classType)
    {
        T entity= null;
        try {
            entity = classType.newInstance();
            Field[] fields = classType.getDeclaredFields();
            if(fields!=null) {
                for (Field field : fields) {
                    if (map.containsKey(field.getName()))
                        field.setAccessible(true);
                        field.set(entity, map.get(field.getName()));
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return entity;
    }

    public List<T> ListToObject(List<Map<String, String>> list, Class<T> classType) {
        List<T> resultList = new ArrayList<T>();
        for (Map<String, String> map : list) {
            T item = DictToObject(map, classType);
            if (item != null)
                resultList.add(item);
        }
        return resultList;
    }
}
