EnumHelper.java 2.41 KB
package com.yanzuoguang.util.helper;

import com.yanzuoguang.util.exception.ExceptionHelper;

import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * 字符串和枚举进行转换
 * @author 颜佐光
 */
public class EnumHelper {

    private static HashMap<Class, Method> CacheMethod = new HashMap<>();


    public static <T extends Enum<T>> T toEnum(String vStr, T vDefault) {
        Class<T> vType = (Class<T>) vDefault.getClass();
        T result = vDefault;
        try {
            if (!StringHelper.isEmpty(vStr)) {
                result = Enum.valueOf(vType, vStr);
            }
        } catch (Exception ex) {
            ExceptionHelper.handleException(EnumHelper.class, ex, vStr);
        }
        return result;
    }

    public static <T> T toEnum(Class<T> vType, String vStr) {
        return toEnum(vType, vStr, null);
    }

    public static <T> T toEnum(Class<T> vType, String vStr, T vDefault) {
        T result = vDefault;
        try {
            if (StringHelper.isInteger(vStr)) {
                result = toEnum(vType, StringHelper.toInt(vStr));
            } else if (!StringHelper.isEmpty(vStr)) {
                result = (T) Enum.valueOf((Class) vType, vStr);
            }
        } catch (Exception ex) {
            ExceptionHelper.handleException(EnumHelper.class, ex, vStr);
        }
        if (result == null && vDefault == null) {
            result = toEnum(vType, 0);
        }
        return result;
    }

    public static <T> T toEnum(Class<T> vType, int i) {
        T result = null;
        try {
            if (CacheMethod.containsKey(vType)) {
                Method met = CacheMethod.get(vType);
                result = (T) met.invoke(null, i);
            } else {
                Method[] vMets = vType.getMethods();
                for (Method vMet : vMets) {
                    String vName = vMet.getName();
                    if ("forValue".equals(vName)
                            && vMet.getParameterTypes().length == 1) {
                        //  Class vTempType = vMet.getParameterTypes()[0];
                        Object obj = vMet.invoke(null, i);
                        result = (T) obj;
                        CacheMethod.put(vType, vMet);
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            ExceptionHelper.handleException(EnumHelper.class, ex, i);
        }
        return result;
    }
}