package com.aiotagro.common.core.utils;

import java.lang.reflect.Field;

/**
 * @author Carson
 * @package_name com.aiotagro.common.core.utils
 * @date 2024/7/9 下午2:32
 */
public class EnumUtil {
    public static <T extends Enum<T>> T getEnumConstant(Class<T> enumClass, int value) {
        for (T enumConstant : enumClass.getEnumConstants()) {
            try {
                Field field = enumConstant.getClass().getDeclaredField("value");
                field.setAccessible(true);
                if (field.getInt(enumConstant) == value) {
                    return enumConstant;
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new IllegalArgumentException("枚举类 " + enumClass.getSimpleName() + " 没有定义 value 字段或访问权限不足", e);
            }
        }
        throw new IllegalArgumentException("在枚举类 " + enumClass.getSimpleName() + " 中未找到对应的值: " + value);
    }
}
