自定义注解学习

自定义注解

文章目录


自定义注解类

package com.example.demo.test;

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

/**
 * BelongsProject: demo
 * BelongsPackage: com.example.demo.test
 * Author: BAIMH
 * CreateTime: 2021-01-29 10:56
 * Description: 自定义注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNULLAndVerify {
    String message();
}

自定义异常类

package com.example.demo.test;

/**
 * BelongsProject: demo
 * BelongsPackage: com.example.demo.test
 * Author: BAIMH
 * CreateTime: 2021-01-29 10:58
 * Description: 自定义异常类
 */
public class CustomerException extends RuntimeException{
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public CustomerException() {
        super();
    }

    public CustomerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public CustomerException(String message, Throwable cause) {
        super(message, cause);
    }

    public CustomerException(String message) {
        super(message);
    }

    public CustomerException(Throwable cause) {
        super(cause);
    }
}

注解校验器

package com.example.demo.test;



import java.lang.reflect.Field;
import java.util.List;

/**
 * BelongsProject: demo
 * BelongsPackage: com.example.demo.test
 * Author: BAIMH
 * CreateTime: 2021-01-29 10:59
 * Description: 注解校验器
 */
public class NotNullValidator {

    public static <T> void validator(T t) throws IllegalArgumentException, IllegalAccessException{
        boolean isThrowException = false;
        StringBuilder errorMessage = new StringBuilder();
        Class<? extends Object> cla = t.getClass();
        //利用反射获取类的所有字段包含私有属性
        Field[] fields = cla.getDeclaredFields();
        for(Field f:fields){
            //判断字段是否有定义NotNull注解
            NotNULLAndVerify notNullAndVerifyAnnotation = f.getAnnotation(NotNULLAndVerify.class);
            if(null != notNullAndVerifyAnnotation){
                f.setAccessible(true); //设置些属性是可以访问的
                Object val = f.get(t);//得到此属性的值
                boolean flag = notNull(val);
                if(!flag){
                    //获取注解上的异常信息
                    errorMessage.append(notNullAndVerifyAnnotation.message()).append(",");
                    isThrowException = true;
                }
            }
        }
        if(isThrowException){
            exceptionMessage(errorMessage.toString());
        }
    }

    /**
     * 判断字段类型以及值是否空
     * @param value
     * @return
     */
    public static boolean notNull(Object value) {
        if(null == value) {
            return false;
        }
        if(value instanceof String && isEmpty(value.toString())) {
            return false;
        }
        if(value instanceof Integer && isEmpty((Integer)value)) {
            return false;
        }
        if(value instanceof List && isEmpty((List<?>) value)) {
            return false;
        }
        if (value instanceof Integer && isage((Integer)value)){
           return false;
        }
        return null != value;
    }

    public static boolean isEmpty(String str) {
        return null == str || str.isEmpty();
    }

    public static boolean isEmpty(List<?> list) {
        return null == list || list.isEmpty();
    }

    public static boolean isEmpty(Integer i){
        return null == i;
    }

    public static boolean isage(Integer i){
        if (null == i){
            return false;
        }
        return i>=12;
    }
    /**
     * 抛出注解对应的异常信息
     * @param errorMessage
     */
    public static void exceptionMessage(String errorMessage) {
        throw new CustomerException(errorMessage);
    }
}

实体类

package com.example.demo.test;

/**
 * BelongsProject: demo
 * BelongsPackage: com.example.demo.test
 * Author: BAIMH
 * CreateTime: 2021-01-29 11:02
 * Description: 实体类
 */
public class Person {
    @NotNULLAndVerify(message = "姓名不能为空")
    private String name;

    @NotNULLAndVerify(message = "年龄不能为空,且年龄小于12岁")
    private Integer age;

    private Double salary;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", salary=" + salary + "]";
    }
}



测试类

package com.example.demo.test;

/**
 * BelongsProject: demo
 * BelongsPackage: com.example.demo.test
 * Author: BAIMH
 * CreateTime: 2021-01-29 11:02
 * Description:
 */
public class Test {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        Person p = new Person();
        p.setSalary(12000d);
        p.setAge(12);
        p.setName("111");
        NotNullValidator.validator(p);
        System.out.println(p);
    }
}

错误

D:\jdk1.8.0_261\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.1.2\lib\idea_rt.jar=53780:D:\IntelliJ IDEA 2020.1.2\bin" -Dfile.encoding=UTF-8 -classpath D:\jdk1.8.0_261\jre\lib\charsets.jar;D:\jdk1.8.0_261\jre\lib\deploy.jar;D:\jdk1.8.0_261\jre\lib\ext\access-bridge-64.jar;D:\jdk1.8.0_261\jre\lib\ext\cldrdata.jar;D:\jdk1.8.0_261\jre\lib\ext\dnsns.jar;D:\jdk1.8.0_261\jre\lib\ext\jaccess.jar;D:\jdk1.8.0_261\jre\lib\ext\jfxrt.jar;D:\jdk1.8.0_261\jre\lib\ext\localedata.jar;D:\jdk1.8.0_261\jre\lib\ext\nashorn.jar;D:\jdk1.8.0_261\jre\lib\ext\sunec.jar;D:\jdk1.8.0_261\jre\lib\ext\sunjce_provider.jar;D:\jdk1.8.0_261\jre\lib\ext\sunmscapi.jar;D:\jdk1.8.0_261\jre\lib\ext\sunpkcs11.jar;D:\jdk1.8.0_261\jre\lib\ext\zipfs.jar;D:\jdk1.8.0_261\jre\lib\javaws.jar;D:\jdk1.8.0_261\jre\lib\jce.jar;D:\jdk1.8.0_261\jre\lib\jfr.jar;D:\jdk1.8.0_261\jre\lib\jfxswt.jar;D:\jdk1.8.0_261\jre\lib\jsse.jar;D:\jdk1.8.0_261\jre\lib\management-agent.jar;D:\jdk1.8.0_261\jre\lib\plugin.jar;D:\jdk1.8.0_261\jre\lib\resources.jar;D:\jdk1.8.0_261\jre\lib\rt.jar;E:\BAI\work\springcloud-demo-master\demo\target\classes;D:\maven\repositories\org\springframework\boot\spring-boot-starter-web\2.4.2\spring-boot-starter-web-2.4.2.jar;D:\maven\repositories\org\springframework\boot\spring-boot-starter\2.4.2\spring-boot-starter-2.4.2.jar;D:\maven\repositories\org\springframework\boot\spring-boot\2.4.2\spring-boot-2.4.2.jar;D:\maven\repositories\org\springframework\boot\spring-boot-autoconfigure\2.4.2\spring-boot-autoconfigure-2.4.2.jar;D:\maven\repositories\org\springframework\boot\spring-boot-starter-logging\2.4.2\spring-boot-starter-logging-2.4.2.jar;D:\maven\repositories\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\maven\repositories\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\maven\repositories\org\apache\logging\log4j\log4j-to-slf4j\2.13.3\log4j-to-slf4j-2.13.3.jar;D:\maven\repositories\org\apache\logging\log4j\log4j-api\2.13.3\log4j-api-2.13.3.jar;D:\maven\repositories\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;D:\maven\repositories\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\maven\repositories\org\yaml\snakeyaml\1.27\snakeyaml-1.27.jar;D:\maven\repositories\org\springframework\boot\spring-boot-starter-json\2.4.2\spring-boot-starter-json-2.4.2.jar;D:\maven\repositories\com\fasterxml\jackson\core\jackson-databind\2.11.4\jackson-databind-2.11.4.jar;D:\maven\repositories\com\fasterxml\jackson\core\jackson-annotations\2.11.4\jackson-annotations-2.11.4.jar;D:\maven\repositories\com\fasterxml\jackson\core\jackson-core\2.11.4\jackson-core-2.11.4.jar;D:\maven\repositories\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.11.4\jackson-datatype-jdk8-2.11.4.jar;D:\maven\repositories\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.11.4\jackson-datatype-jsr310-2.11.4.jar;D:\maven\repositories\com\fasterxml\jackson\module\jackson-module-parameter-names\2.11.4\jackson-module-parameter-names-2.11.4.jar;D:\maven\repositories\org\springframework\boot\spring-boot-starter-tomcat\2.4.2\spring-boot-starter-tomcat-2.4.2.jar;D:\maven\repositories\org\apache\tomcat\embed\tomcat-embed-core\9.0.41\tomcat-embed-core-9.0.41.jar;D:\maven\repositories\org\glassfish\jakarta.el\3.0.3\jakarta.el-3.0.3.jar;D:\maven\repositories\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.41\tomcat-embed-websocket-9.0.41.jar;D:\maven\repositories\org\springframework\spring-web\5.3.3\spring-web-5.3.3.jar;D:\maven\repositories\org\springframework\spring-beans\5.3.3\spring-beans-5.3.3.jar;D:\maven\repositories\org\springframework\spring-webmvc\5.3.3\spring-webmvc-5.3.3.jar;D:\maven\repositories\org\springframework\spring-aop\5.3.3\spring-aop-5.3.3.jar;D:\maven\repositories\org\springframework\spring-context\5.3.3\spring-context-5.3.3.jar;D:\maven\repositories\org\springframework\spring-expression\5.3.3\spring-expression-5.3.3.jar;D:\maven\repositories\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;D:\maven\repositories\org\springframework\spring-core\5.3.3\spring-core-5.3.3.jar;D:\maven\repositories\org\springframework\spring-jcl\5.3.3\spring-jcl-5.3.3.jar com.example.demo.test.Test
Exception in thread "main" com.example.demo.test.CustomerException: 年龄不能为空,且年龄小于12岁,
	at com.example.demo.test.NotNullValidator.exceptionMessage(NotNullValidator.java:89)
	at com.example.demo.test.NotNullValidator.validator(NotNullValidator.java:38)
	at com.example.demo.test.Test.main(Test.java:16)

Process finished with exit code 1```

上一篇:修改docker中alpine镜像为国内源


下一篇:github复制Repositories报错