Java反射获取枚举类型值列表对外提供服务

一、前言

在工作中原本一些枚举值都是在Apollo配置的,但是有一些配置没有必要从配置中心获取,比如简单的类型下拉框的选择和页面回显。
实现的原理很简单,就是通过自定义注解,加在需要对外提供的枚举类上。我这里是定义了三个注解(类标记,key标志,value标记)

二、关键代码实现

/**
 * @description 枚举类标记,标记了会对外提供列表,默认取类名称
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
@Documented
public @interface EnumValue {
    /**
     * 枚举接口匹配key,默认类名
     *
     * @return
     */
    String name() default "";
}

/**
 * @description 枚举标记,标记了会对外提供列表
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
@Documented
public @interface EnumLabelField {
}

/**
 * @description 枚举value标记
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
@Documented
public @interface EnumValueField {
}

我这里反射使用的是扫描工具,依赖:

implementation group: 'org.reflections', name: 'reflections', version: '0.10.2'
/**
 * @description 枚举服务类,获取枚举类的枚举值列表
 */
@Slf4j
@Service("enumAppService")
public class EnumAppServiceImpl implements EnumAppService {
    /**
     * 枚举类扫描包路径
     */
    private static final String PACKAGE_PATH = "com.yingzi.idp.edge.app.v2.dto.enums";
    /**
     * 枚举类Map
     */
    private static final Map<String, List<EnumValueResDto>> enumMap = new HashMap();

    @PostConstruct
    public void init() {
        Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(PACKAGE_PATH));
        // 扫描特定包下带有 EnumValue 注解的枚举类
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(EnumValue.class);
        if (CollUtil.isEmpty(classSet)) {
            return;
        }
        try {
            for (Class<?> clazz : classSet) {
                Field[] fields = clazz.getDeclaredFields();
                Field valueField = null;
                Field labelField = null;
                for (Field field : fields) {
                    EnumLabelField enumLabelField = field.getDeclaredAnnotation(EnumLabelField.class);
                    if (Objects.nonNull(enumLabelField)) {
                        field.setAccessible(true);
                        labelField = field;
                        continue;
                    }
                    EnumValueField enumValueField = field.getDeclaredAnnotation(EnumValueField.class);
                    if (Objects.nonNull(enumValueField)) {
                        field.setAccessible(true);
                        valueField = field;
                    }
                }
                if (Objects.isNull(valueField) || Objects.isNull(labelField)) {
                    log.error("枚举值标记没有找到对应的value和label字段标记");
                    continue;
                }
                // 反射 values 方法,获取枚举值数组
                Method method = clazz.getMethod("values");
                Object[] enums = (Object[]) method.invoke(null);
                List<EnumValueResDto> resDtoList = new ArrayList<>(enums.length);
                for (Object e : enums) {
                    Object value = valueField.get(e);
                    Object label = labelField.get(e);
                    EnumValueResDto resDto = new EnumValueResDto(String.valueOf(label), String.valueOf(value));
                    resDtoList.add(resDto);
                }
                // 默认取类名作为key
                EnumValue enumValue = clazz.getAnnotation(EnumValue.class);
                String name = StringUtils.isBlank(enumValue.name()) ? clazz.getSimpleName() : enumValue.name();
                enumMap.put(name, resDtoList);
            }
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<EnumValueResDto> getEnumValueList(String key) {
        return enumMap.get(key);
    }
}

最后前端只需要传参 key,就可以获取到对应key的枚举列表啦,这种方法挺简单的,希望对你有帮助。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值