package com.ibiz.util.helper;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

/**
 * 实体对象属性缓存类
 */
public class CacheFieldMap {

	private static Hashtable<String, Hashtable<String,Field>> cacheMap = new Hashtable<>();

	/**
	 * 将实体对象中的属性存入缓存中
	 * @param className
	 * @return
	 */
	public static Hashtable<String,Field> getFieldMap(String className) {
		if(className.indexOf("_$")>0)
			className=className.substring(0, className.lastIndexOf("_$"));
		Class clazz = null;
		try {
			clazz = Class.forName(className);
		}
		catch (Exception ex) {
			return new Hashtable<String,Field>();
		}
		if(cacheMap.containsKey(className))
			return cacheMap.get(className);
		synchronized (CacheFieldMap.class) {
			Hashtable<String,Field> result = cacheMap.get(className);
			if (result == null) {
				result=new Hashtable<String,Field>();
				Field[] fields=clazz.getDeclaredFields();
				for(Field field:fields){
					result.put(field.getName(),field);
				}
				cacheMap.put(className, result);
			}
			return result;
		}
	}

	/**
	 * 从缓存中查询实体对象属性列表
	 * @param className
	 * @return
	 */
	public static List<Field> getFields(String className) {
		if(className.indexOf("_$")>0)
			className=className.substring(0, className.lastIndexOf("_$"));
		Hashtable<String,Field> fieldmap=cacheMap.get(className);
		if(fieldmap==null)
			fieldmap= CacheFieldMap.getFieldMap(className);
		Iterator it = fieldmap.keySet().iterator();
		List<Field> list=new ArrayList<Field>();
		while(it.hasNext()) {
			Object key = it.next();
			if(fieldmap.get(key.toString())!=null)
				list.add(fieldmap.get(key.toString()));
		}
		return list;
	}
}