案例:检查空字段【注解+反射+自定义异常】

学习永不止步!
一个结合了注解、反射、自定义异常知识的小案例——检查空字段!

1、定义一个规范类:凡是需要进行字段检查都需要实现

package com.dongzi;

/**
 * 定义规范化接口
 */
public interface CheckRule {
}

2、定义实体类并实现规范接口:需要进行字段检查的需要加上CheckField注解,第3项附代码

package com.dongzi;

/**
 * 模拟实体类
 */
public class Student implements CheckRule {

    public Student() {

    }

    public Student(Integer id, Integer age, Integer sex, String name) {
        this.id = id;
        this.age = age;
        this.sex = sex;
        this.name = name;
    }

    private Integer id;

    @CheckField(message = "学生年龄")
    private Integer age;

    private Integer sex;

    @CheckField(message = "学生姓名")
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3、定义检查字段注解

package com.dongzi;

import java.lang.annotation.*;

/**
 * 定义检查字段的注解
 * <pre>
 *     @Retention:指定运行时
 *     @Target:指定注解作用范围
 * </pre>
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CheckField {

    /**
     * 是否开启字段NULL值检查
     * @return true 默认返回检查开启字段
     */
    boolean value() default true;

    /**
     * 字段相关描述
     */
    String message();
}

4、自定义异常:检查到字段为NULL时抛出

package com.dongzi;

/**
 * 自定义检查异常
 */
public class CheckException extends Exception{

    /**
     * 无特殊实现直接调用父类构造
     * @param msg 异常消息
     */
    public CheckException(String msg){
        super(msg);
    }
}

5、定义检查字段工具类:检查字段的方法

package com.dongzi;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 定义异常检查工具类
 */
public class CommentUtils {

    /**
     * 检查空字段工具类
     *
     * @param checkRule 需要被检查的bean
     */
    public static void checkNonField(CheckRule checkRule) throws CheckException {
        Class<? extends CheckRule> beanClass = checkRule.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        if (fields.length > 0) {
            for (Field field : fields) {
                CheckField checkField = field.getAnnotation(CheckField.class);
                if (checkField != null && checkField.value()) {
                    // field.setAccessible(true);
                    String fieldName = field.getName();
                    // TODO:没引入其他工具类,暂代
                    char[] chars = fieldName.toCharArray();
                    chars[0] = Character.toUpperCase(chars[0]);
                    fieldName = String.copyValueOf(chars);
                    String methodName = "get" + fieldName;
                    Object objVal;
                    try {
                        objVal = beanClass.getMethod(methodName).invoke(checkRule);
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        // method invoke异常处理
                    }

                    if (objVal == null || "".equals(objVal)) {
                        throw new CheckException(checkField.message() + ":为必填项");
                    }
                }
            }
        }
    }
}

6、程序开始

package com.dongzi;

public class Main {

    public static void main(String[] args) {
        // Student student_1 = new Student(1, 23, 1, "法外狂徒——张三"); // 输出结果:~~~字段不为NULL
        Student student_2 = new Student(1, null, 1, "法外狂徒——张三"); // 输出结果:学生年龄:为必填项

        try {
            CommentUtils.checkNonField(student_2);
            System.out.println("~~~字段不为NULL");
        } catch (CheckException e) {
            e.printStackTrace();
        }

    }
}

7、两种执行结果

  • 传入student_1对象:
    传入student_1
  • 传入student_2对象:
    传入student_2
    抛出异常,NULL字段检查完成!可完成一个Bean里面所有非空字段的检查。

附1:项目结构

在这里插入图片描述

附2:关于反射执行效率

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白说(๑• . •๑)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值