Java自定义注解以及注解校验的相关逻辑

业务逻辑:将前端传来的参数字段中的小写字母转成大写字母

实现逻辑:通过自定义注解实现转换,在相关的字段上添加指定注解,实现转换。

实现目标:

 

 

 

步骤一:自定义注解(具体方法我这里就不介绍了,百度一大堆),直接看代码

...
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author wzj
 */
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RemoveSpaceAndToUpperCase {

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

步骤二:通过切面前置通知(忽略我的切入点命名)、反射获取变量对象属性值,从而实现转换

   @Order(2)
    @Before("errorController()")
    public void removeSpaceAndToUpperCase(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (Objects.isNull(arg) || "".equals(arg)) {
                return;
            }
            //获取相关类的所以属性(getFields()无法获取private属性的字段)
            Field[] fields = arg.getClass().getDeclaredFields();
            for (Field field : fields) {
                //是否使用RemoveSpaceAndToUpperCase注解
                if (field.isAnnotationPresent(RemoveSpaceAndToUpperCase.class)) {
                    for (Annotation annotation : field.getDeclaredAnnotations()) {
                        //是否是自定义的RemoveSpaceAndToUpperCase注解
                        if (annotation.annotationType().equals(RemoveSpaceAndToUpperCase.class)) {
                            try {
                                //不去检查Java语言权限控制(如private)
                                field.setAccessible(true);
                                if (Objects.isNull(field.get(arg)) || "".equals(field.get(arg))) {
                                    return;
                                }
                                //实现方法
                                String str = StringUtil.removeSpaceAndToUpperCase(field.get(arg).toString());
                                field.set(arg, str);
                            } catch (IllegalAccessException e) {
                                log.error(DefaultConstant.ILLEGAL_ARGUMENT_BUSINESS_EXCEPTION.getMessage(), e);
                                throw new CheckException(DefaultConstant.ILLEGAL_ARGUMENT_BUSINESS_EXCEPTION);
                            }
                        }
                    }
                }
            }
        }
    }

步骤三:我写的实现现仅支持这种传参:

 

 

 暂不支持这种传参校验:

 

 

 

JoinPoint详解:https://blog.csdn.net/qq_15037231/article/details/80624064
Field反射详解:http://www.51gjie.com/java/795.html
posted @ 2020-12-07 21:47  七色光!  阅读(1364)  评论(0编辑  收藏  举报