管道基础大数据平台系统开发-【后端】-Server
1
sws
2022-11-26 ab849f796bdc17236a95ea5fe5c166fb8f24a75c
src/main/java/com/lf/server/helper/EnumHelper.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,83 @@
package com.lf.server.helper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Method;
/**
 * æžšä¸¾å¸®åŠ©ç±»
 * @author WWW
 */
public class EnumHelper {
    private static final String GETTER_PREFIX = "get";
    private static Log log = LogFactory.getLog(EnumHelper.class);
    /**
     * æ ¹æ®åç§°èŽ·å–æžšä¸¾
     *
     * @param clazz æžšä¸¾ç±»åž‹
     * @param name  æžšä¸¾çš„名称,如:SqlParamType中的AND
     * @return è¿”回枚举值
     */
    public static <T extends Enum<T>> T nameOf(Class<T> clazz, String name) {
        return Enum.valueOf(clazz, name);
    }
    /**
     * æ ¹æ®å±žæ€§å+值获取枚举
     *
     * @param clazz        æžšä¸¾ç±»åž‹
     * @param propertyName å­—段,如name,id
     * @param value        å€¼,如张三
     * @return è¿”回枚举值
     */
    public static <T extends Enum<T>> T getByString(Class<T> clazz, String propertyName, String value) {
        String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName);
        T result = null;
        try {
            T[] arr = clazz.getEnumConstants();
            Method targetMethod = clazz.getDeclaredMethod(getterMethodName);
            String typeCodeVal = null;
            for (T entity : arr) {
                typeCodeVal = targetMethod.invoke(entity).toString();
                if (typeCodeVal.contentEquals(value)) {
                    result = entity;
                    break;
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return result;
    }
    /**
     * æ ¹æ®æ•´æ•°èŽ·å–æžšä¸¾
     *
     * @param clazz        æžšä¸¾ç±»åž‹
     * @param propertyName å­—段,如 age
     * @param value        å€¼,如18
     * @return è¿”回枚举值
     */
    public static <T extends Enum<T>> T getByInt(Class<T> clazz, String propertyName, int value) {
        String getterMethodName = GETTER_PREFIX + StringHelper.firstCharToUpperCase(propertyName);
        T result = null;
        try {
            T[] arr = clazz.getEnumConstants();
            Method targetMethod = clazz.getDeclaredMethod(getterMethodName);
            int typeCodeVal;
            for (T entity : arr) {
                typeCodeVal = Integer.parseInt(targetMethod.invoke(entity).toString());
                if (typeCodeVal == value) {
                    result = entity;
                    break;
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return result;
    }
}