先建一个枚举基类
- package com.example.common.enums;
-
-
- import com.baomidou.mybatisplus.annotation.IEnum;
-
- import java.io.Serializable;
-
- /**
- * 枚举基类
- * @param
- */
- public interface IEnumWithStr<T extends Serializable> extends IEnum<T> {
- String getStrValue();
-
- static <E extends Serializable, T extends IEnum<E>>T getByValue(Class
enumClass, Integer value) { - if (value == null) {
- return null;
- }
- for (T tmp : enumClass.getEnumConstants()) {
- if (tmp.getValue().equals(value)) {
- return tmp;
- }
- }
- throw new IllegalArgumentException("No element matches " + value);
- }
- }
再新建一个枚举,并重新实现这个基类里面的getStrValue方法
- package com.example.common.enums;
-
- import com.baomidou.mybatisplus.annotation.EnumValue;
- import com.baomidou.mybatisplus.annotation.IEnum;
- import com.fasterxml.jackson.annotation.JsonValue;
- import lombok.Getter;
-
- /**
- * 变量类别,枚举,用于展示在变量插入的类别
- * 基本信息,薪酬信息,其他等、常量
- */
- @Getter
- public enum CategoryEnum implements IEnumWithStr<Integer> {
- BASE(1,"基本信息"),
- SALARY(2,"薪酬信息"),
- CONSTANT(3,"常量"),
- OTHER(4,"其他");
-
- private Integer code;
- private String msg;
-
- CategoryEnum(Integer code, String msg) {
- this.code = code;
- this.msg = msg;
- }
-
- /**
- * 返回值,加@JsonValue的注解就是在返回前端的时候返回枚举值,而不是json字符串
- * @return
- */
- @Override
- @JsonValue
- public Integer getValue() {
- return this.code;
- }
-
- @Override
- public String getStrValue() {
- return this.msg;
- }
- }
controller建个接口,具体实现应该在service,但是为了表达意思就直接写在controller里面了
先初始化,需要返回到前端的枚举
具体实现如下:
-
- @GetMapping("/getSelect")
- public <T> CommonResult< OfferFieldOptionDTO> getEnums(@RequestParam String key) {
- Class<?> aClass = enumsMap.get(key);
- if (aClass == null) {
- return CommonResult.success(null);
- }
- Class<?> enumClass = enumsMap.get(key);
- OfferFieldOptionDTO fieldOptionDTO = new OfferFieldOptionDTO();
- if (enumClass != null) {
- List<OptionDTO> optionDTOList = new ArrayList<>();
- IEnumWithStr<?>[] enums = (IEnumWithStr[]) enumClass.getEnumConstants();
- for (IEnumWithStr<?> anEnum : enums) {
- OptionDTO optionDTO = new OptionDTO();
- optionDTO.setName(anEnum.getStrValue().toString());
- optionDTO.setValue(anEnum.getValue().toString());
- optionDTOList.add(optionDTO);
- // 将Map添加到集合中
- }
- fieldOptionDTO.setOptions(optionDTOList);
- }
- return CommonResult.success(fieldOptionDTO);
-
- }
最后返回的结果如下:
- {
- "code": 200,
- "message": "操作成功",
- "data": {
- "options": [
- {
- "value": "1",
- "name": "基本信息"
- },
- {
- "value": "2",
- "name": "薪酬信息"
- },
- {
- "value": "3",
- "name": "常量"
- },
- {
- "value": "4",
- "name": "其他"
- }
- ]
- }
- }