package com.org.hktshop.utils;


import java.beans.Introspector;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassUtils {
	 /**
     * Map keyed by class containing CachedIntrospectionResults.
     * Needs to be a WeakHashMap with WeakReferences as values to allow
     * for proper garbage collection in case of multiple class loaders.
     */
//    private static final Map<String, Field[]> classCache =
//    		Collections.synchronizedMap(new WeakHashMap<String, Field[]>());
    /**
     * 获取类本身的BeanInfo，
     * 
     * @param clazz
     * @return
     */
    public synchronized static List<Field > getSelfBeanInfo(Class<?> clazz) {
    	Map<String, Field[]> classCache = new HashMap<>();
    	List<Field > pList = new ArrayList<>();
        try {
            Class<?> classToFlush = clazz;
            do {
                classCache.put(classToFlush.getName(), classToFlush.getDeclaredFields());
                Introspector.flushFromCaches(classToFlush);
                classToFlush = classToFlush.getSuperclass();
            } while (classToFlush != null && !"java.lang.Object".equals(classToFlush.getName()));
            
            for(Field[] pds: classCache.values()){
            	pList.addAll(Arrays.asList(pds));
            }
           
        } catch (Exception e) {
        	e.getStackTrace();
        }
        return pList;
    }
    
    /**
     * 获取类本身的BeanInfo，
     * 
     * @param clazz
     * @return
     */
    public synchronized static Map<String,String> getSelfBeanMap(Class<?> clazz) {
    	Map<String ,String > map = new HashMap<>();
    	Map<String, Field[]> classCache = new HashMap<>();
        try {
            Class<?> classToFlush = clazz;
            do {
                classCache.put(classToFlush.getName(), classToFlush.getDeclaredFields());
                Introspector.flushFromCaches(classToFlush);
                classToFlush = classToFlush.getSuperclass();
            } while (classToFlush != null && !"java.lang.Object".equals(classToFlush.getName()));
            
            for(Map.Entry<String, Field[]> in_entry: classCache.entrySet()){
            	for(Field f : in_entry.getValue()){
            		map.put(f.getName(), in_entry.getKey());
            	}
            }
           
        } catch (Exception e) {
        	e.getStackTrace();
        }
        return map;
    }
    /**
     * 初始化实例
     * 
     * @param clazz
     * @return
     */
    public static Object newInstance(Class<?> clazz) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
//            LOG.error("根据class创建实例失败", e);
//            throw new MincoderException(e);
        	e.getStackTrace();
        }
        return null;
    }
}
