package com.eversec.common;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;

/**
 * Created by liangxianyou@eversec.cn at 2018/3/12 14:17.
 */
public class Kv<K,V> extends LinkedHashMap {
    public static Kv of(){
        return new Kv();
    }

    public static Kv of(Object k, Object v){
        return new Kv().set(k,v);
    }

    public Kv<K, V> set(K k, V v){
        put(k, v);
        return this;
    }

    public static Kv toKv(Object m) {
        return toKv(m, Kv.of(), m.getClass());
    }

    private static Kv toKv(Object m, Kv kv, Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                if (!kv.containsKey(field.getName())) {
                    kv.set(field.getName(), field.get(m));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        Class superclass = clazz.getSuperclass();
        if (superclass != null) {
            kv = toKv(m, kv, superclass);
        }
        return kv;
    }
}