JAVA入参注解方式校验枚举类

废话不多说,直接上代码

Controller层



public Result<Void> save(@Valid @RequestBody GameResult gameResult){
    gameService.saveGameResult(gameResult);
    return Result.success();
}

入参


public class GameResult{

    @ApiModuleProperties("用户ID")
    private String userId;

    @Enum(value = GameResultEnum.class, message = "游戏结果类型错误!1-胜利;0-失败;-1-逃跑")
    @ApiModuleProperties("游戏结果")
    private Integer result;

}

自定义Enum注解

@Target(FIELD)
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = EnumValidator.class)
public @interface Enum {

    String DEFAULT_MESSAGE = "不在指定枚举值范围内\n";

    String message() default DEFAULT_MESSAGE;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<?> value();

    String enumMethod() default "getKey";
}

校验类

@Slf4j
public class EnumValidator implements ConstraintValidator<Enum, Integer>{

    private Set<Integer> set = new HashSet<>();

    @Override
    public void initialize(Enum constraintAnnotation){

        if(null == constraintAnnotation){
        
            return;
        
        }

        Class<?> clazz = constraintAnnotation.value();
        
        String methodName = constraintAnnotation.enumMethod();

        if(clazz.isEnum()){
            
            Method getCode;
            
            Object[] objs = clazz.getEnumConstants();

            try{
                
                getCode = clazz.getMehtod(methodName);
        
                if(null == getCode){
                    
                    throw new RuntimeException("enum method can not be null, methodName:" + methodName);
              
                  }

                for(Object obj : objs){
                    
                    Integer code = (Integer)getCode.invoke(obj);

                    set.add(code);

                }

            }catch(Exception e){

                log.error("EnumValitor error", e);
                
                throw new RuntimeException(e);

            }
        }
        
    }

}

枚举类

public enum GameResultEnum{


    WIN(1),

    LOSE(0),

    RUN_AWAY(-1);

    
    private Integer key;


    GameResultEnum(Integer key){
        
        this.key = key;

    }

    public Integer getKey(){

        return key;

    }

}

目前这套代码只支持整数类型枚举值,如果是其他类型的枚举值需要调整一下,只是给各位大佬提供一个思路。

以上。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值