通过反射获取枚举值

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

示例枚举定义


import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zbwd.exception.BizException;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 事故类型
 *
 * @author yzd
 */
@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum AccidentEnum {
    /**
     * 事故类型
     */
    FIRE(1L, "火灾"),

	// 该注解 在返回值 时 忽略 该字段
    @JsonIgnore
    WATER(2L, "水灾"),

    ;
    private final Long id;

    private final String name;

    /**
     * 根据标识 获取 事故 名称
     *
     * @param id 事故标识
     * @return 事故 名称
     */
    public static String getNameById(Long id) {
        for (AccidentEnum value : AccidentEnum.values()) {
            if (value.getId().equals(id)) {
                return value.getName();
            }
        }
        throw new BizException("该事故类型不存在");
    }

}
复制代码

反射获取枚举值controller


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.zbwd.exception.BizException;
import com.zbwd.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yzd
 * 枚举管理
 */
@Slf4j
@Api(tags = "枚举管理")
@RestController
@RequestMapping("/enums/enum")
public class EnumsController {

	// 包名 按实际情况修改
    private static final String ENUM_PACKAGE_LOCALTION = "com.zbwd.plan.constant.";

    @GetMapping("/{enumName}")
    public JsonResult getEnums(@ApiParam(value = "LevelEnum:分级响应 ; AccidentEnum: 事故类型") @PathVariable String enumName) {
        String clazz = ENUM_PACKAGE_LOCALTION + enumName;
        Class<?> aClass;
        try {
            aClass = Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            log.error("该枚举类型不存在", e);
            throw new BizException("该枚举类型不存在");
        }
        // 根据注解忽略 值
        List<String> nameList = new ArrayList<>(aClass.getFields().length);
        if (aClass.getFields().length > 0) {
            Arrays.stream(aClass.getFields()).forEach(item -> {
                if (item.getAnnotations().length > 0) {
                    for (Annotation annotation : item.getAnnotations()) {
                        if (annotation instanceof JsonIgnore) {
                            nameList.add(item.getName());
                        }
                    }
                }
            });
        }
        // 没有忽略 字段注解
        if (CollectionUtils.isEmpty(nameList)) {
            return JsonResult.success(aClass.getEnumConstants());
        }
        // 过滤后的  list
        List<?> objects = Arrays.stream(aClass.getEnumConstants())
                .filter(item -> !nameList.contains(item.toString()))
                .collect(Collectors.toList());

        return JsonResult.success(objects);
    }

}
复制代码

猜你喜欢

转载自juejin.im/post/7110405511878541319