Java 自定义注解 不能为空

在Java开发中,我们经常需要对方法、类、变量等进行注解,以便在运行时获取注解信息并执行相应的操作。而有时,我们需要对注解进行一些限制,比如对注解的属性值进行非空校验。本文将介绍如何通过自定义注解,在编译时对注解的属性进行非空校验。

自定义注解

首先,我们需要定义一个自定义注解 NotNull,用于标识需要进行非空校验的属性。可以通过以下方式定义该注解:

public @interface NotNull {
}

上述代码中,@interface 关键字用于定义一个注解。接下来,我们需要在该注解中添加属性,以便在使用注解时传入相应的值。修改注解的定义如下:

public @interface NotNull {
    String message() default "不能为空";
}

在上述代码中,我们添加了一个属性 message,用于存储非空校验失败时的提示信息,默认值为 "不能为空"。接下来,我们需要编写一个非空校验的工具类,用于在编译时对注解进行校验。

非空校验工具类

public class NotNullValidator {
    public static void validate(Object obj) {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(NotNull.class)) {
                field.setAccessible(true);
                try {
                    if (field.get(obj) == null) {
                        String message = field.getAnnotation(NotNull.class).message();
                        throw new IllegalArgumentException(message);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在上述代码中,我们通过反射获取传入对象的所有字段,并遍历每个字段。判断字段是否被 NotNull 注解标注,如果是,则将字段设置为可访问,并判断其值是否为空。如果为空,则抛出 IllegalArgumentException 异常,并将注解中定义的提示信息作为异常信息。

使用示例

下面我们通过一个示例来演示如何在编译时对注解的属性进行非空校验。

public class User {
    @NotNull(message = "用户名不能为空")
    private String username;

    @NotNull(message = "密码不能为空")
    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    // 省略其他代码
}

在上述代码中,我们在 usernamepassword 字段上添加了 @NotNull 注解,并传入了相应的提示信息。

接下来,我们在一个测试类中使用该注解:

public class Main {
    public static void main(String[] args) {
        User user1 = new User("admin", null);
        User user2 = new User(null, "123456");

        try {
            NotNullValidator.validate(user1);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        try {
            NotNullValidator.validate(user2);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

在上述代码中,我们创建了两个 User 对象,其中一个对象的 password 属性为空,另一个对象的 username 属性为空。我们通过 NotNullValidator 类的 validate 方法对这两个对象进行非空校验,并捕获可能抛出的异常。如果属性值为空,则会输出相应的提示信息。

总结

通过自定义注解,我们可以对属性、方法等进行标注,以便在运行时获取注解信息并执行相应的逻辑。而添加一些限制条件,比如非空校验,可以有效提高代码的健壮性和可维护性。本文介绍了如何通过自定义注解进行非空校验,并提供了相应的示例代码。希望本文对你理解和使用自定义注解有所帮助。


gantt
    dateFormat  YYYY-MM-DD
    title       Java 自定义注解 不能为空
    section     定义注解
    定义注解       :2022-12-01, 1d
    section     实现非空校验工具类
    实现非空校验工具类  :2022-12-02, 2