java自定义注解实现对象属性的非空校验

1.首先定义NotNull注解

package com.example.demo;

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

/**
 * 自定义属性非空校验注解
* @Author: wwh
* @Date: 2019/1/16 15:19:10
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {

    /**
     * 获取参数名
     * @return
     */
    String fileName();
}

2.定义一个通用校验返回结果类

package com.example.demo;

/**
 * @program: demo
 * @description:
 * @author: wwh
 * @create: 2019-01-16 14:28
 **/
public class ValidateResult {
    private boolean isValid = true;
    private String message;

    public ValidateResult() {
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.isValid = false;
        this.message = message;
    }

    public boolean isValid() {
        return this.isValid;
    }
}


3.定义一个MyAnnotation类,其中定义validate方法,用来实现校验的处理逻辑

package com.example.demo;

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

/**
 * @program: demo
 * @description:
 * @author: wwh
 * @create: 2019-01-16 14:25
 **/
public class MyAnnotation {

    public static  List validate(T t){
        List validateResults = new ArrayList<>();
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field:fields) {
            if (field.isAnnotationPresent(NotNull.class)) {
                field.setAccessible(true);
                Object value = null;
                try {
                    value = field.get(t);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (value==null) {
                    NotNull notNull = field.getAnnotation(NotNull.class);
                    ValidateResult validateResult = new ValidateResult();
                    validateResult.setMessage(notNull.fileName()+"不能为空");
                    validateResults.add(validateResult);
                }
            }
            
        }
        return validateResults;
    }
}

4.定义pojo对象,在属性上加上@NotNull注解

package com.example.demo;

/**
 * @program: demo
 * @description:
 * @author: wwh
 * @create: 2019-01-16 14:40
 **/
public class Person {

    @NotNull(fileName = "姓名")
    private String name;
    @NotNull(fileName = "年龄")
    private String age;

    /**
     * 获取 @NotNull(fileName = "姓名")
     *
     * @return name @NotNull(fileName = "姓名")
     */
    public String getName() {
        return this.name;
    }

    /**
     * 设置 @NotNull(fileName = "姓名")
     *
     * @param name @NotNull(fileName = "姓名")
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取 @NotNull(fileName = "年龄")
     *
     * @return age @NotNull(fileName = "年龄")
     */
    public String getAge() {
        return this.age;
    }

    /**
     * 设置 @NotNull(fileName = "年龄")
     *
     * @param age @NotNull(fileName = "年龄")
     */
    public void setAge(String age) {
        this.age = age;
    }
}

5.编写测试类

package com.example.demo;

import java.util.List;

/**
 * @program: demo
 * @description:
 * @author: wwh
 * @create: 2019-01-16 15:32
 **/
public class MyTest {
    public static void main(String[] args) {
        Person person = new Person();
//        person.setName("张飞");
//        person.setAge("128");
        List validate = MyAnnotation.validate(person);
        StringBuilder str = new StringBuilder();
        for (ValidateResult va : validate) {
            if (!va.isValid()) {
                str.append(va.getMessage()).append(",");
            }
        }
        System.err.println(str.toString());
    }
}

输出结果为:

姓名不能为空,年龄不能为空,

你可能感兴趣的:(java)