All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.leopard.burrow.lang.inum.EnumUtil Maven / Gradle / Ivy

package io.leopard.burrow.lang.inum;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EnumUtil {

	protected static final Map>> cache = new ConcurrentHashMap>>();

	// public static > EnumSet of(E e) {

	public static > String getDesc(Object key, Class clazz) {
		// Onum obj = EnumUtil.toEnum(key, clazz);
		E e = EnumUtil.get(key, clazz);
		if (e == null) {
			return null;
		}
		@SuppressWarnings("unchecked")
		Onum onum = (Onum) e;
		return (String) onum.getDesc();
	}

	/**
	 * 根据ID转换为枚举(元素不存在会抛异常).
	 * 
	 * @param id
	 * @param clazz
	 * @return
	 */
	public static > E toEnum(Object key, Class clazz) {
		E inum = get(key, clazz);
		if (inum == null) {
			throw new IllegalArgumentException("枚举元素[" + key + "]不存在.");
		}
		return inum;
	}

	/**
	 * 根据ID转换为枚举(元素不存在返回onum).
	 * 
	 * @param key
	 * @param clazz
	 * @param onum
	 * @return
	 */
	public static > E toEnum(Object key, Class clazz, E onum) {
		E inum = get(key, clazz);
		if (inum == null) {
			return onum;
		}
		return inum;
	}

	/**
	 * 判断key是否存在.
	 * 
	 * @param key
	 * @param clazz
	 * @return
	 */
	public static > boolean contains(Object key, Class clazz) {
		key = toLowerCase(key);
		Map> map = cache.get(key);
		if (map == null) {
			map = toMap(key, clazz);
		}
		return map.containsKey(key);
	}

	/**
	 * 根据ID转换为枚举(元素不存在则返回null,不抛异常)
	 * 
	 * @param id
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static > E get(Object key, Class clazz) {
		key = toLowerCase(key);
		Map> map = cache.get(key);
		if (map == null) {
			map = toMap(key, clazz);
		}
		return (E) map.get(key);
	}

	@SuppressWarnings("unchecked")
	protected static synchronized > Map> toMap(Object key, Class clazz) {
		Map> map = cache.get(key);
		if (map != null) {
			return map;
		}
		map = new HashMap>();
		EnumSet set = EnumSet.allOf(clazz);
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Onum value = (Onum) iterator.next();
			Object id = value.getKey();
			id = toLowerCase(id);
			map.put(id, (Enum) value);
		}
		// cache.put(key, map);
		cache.put(clazz.getName(), map);
		return map;
	}

	protected static Object toLowerCase(Object key) {
		if (key instanceof String) {
			return ((String) key).toLowerCase();// 统一转成小写保存
		}
		else {
			return key;
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy