Java注解特性

Java注解介绍

注解又叫做元数据,以一种形式化的方式为我们在代码中添加规则,使我们无须手动去获取数据,可以通过注解定义的规则,在我们需要的时刻,随时获取数据。

元注解

  • @Target:表示该注解可以用于什么地方,就是注解使用的目标对象
    @Target(ElementType.TYPE) :类、接口(包括注解类型)或enum声明。
    @Target(ElementType.FIELD):字段、枚举的常量。
    @Target(ElementType.METHOD):METHOD:方法声明。
    @Target(ElementType.PARAMETER):方法参数声明。
    @Target(ElementType.CONSTRUCTOR):构造器的声明。
    @Target(ElementType.LOCAL_VARIABLE):局部变量声明。
    @Target(ElementType.ANNOTATION_TYPE):注解类型声明。
    @Target(ElementType.PACKAGE):包声明。
  • @Retention:表示需要在什么级别保存该注解信息,就是注解保存的策略。
    @Retention(RetentionPolicy.SOURCE):注解将被编译器丢弃。
    @Retention(RetentionPolicy.CLASS):注解在class文件中可用,在jvm中丢弃。
    @Retention(RetentionPolicy.RUNTIME):jvm在运行期也保留注解,可以通过反射机制来读取注解的信息。
  • @Documented:将此注解包含在Javadoc中。
  • @Inherited:允许子类继承父类中的注解。

自定义注解实战,字段校验

/**
 * 字符串判空校验
 * @author sunpy
 *
 */
@Documented
@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SunpyValidateString {
    boolean isEmpty();
}

/**
 * int/Integer最大值校验
 * @author Administrator
 *
 */
@Documented
@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SunpyValidateMax {
    int max();
}

/**
 * int/Integer最小值校验
 * @author sunpy
 *
 */
@Documented
@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SunpyValidateMin {
    int min(); 
}
/**
 * 注解模型类
 * @author sunpy
 *
 */
public class User {

    @SunpyValidateString(isEmpty = false)
    private String username;

    @SunpyValidateMax(max = 120)
    @SunpyValidateMin(min = 1)
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
/**
 * 注解解析器
 * @author sunpy
 *
 */
public class ValidatorResolver {
    
    public static <T> boolean validate(T t) throws Exception {
        Field[] fields = t.getClass().getDeclaredFields();
        
        for (Field field : fields) {
            field.setAccessible(true);
            SunpyValidateString sunpyValidateString = field.getAnnotation(SunpyValidateString.class);
            SunpyValidateMax sunpyValidateMax = field.getAnnotation(SunpyValidateMax.class);
            SunpyValidateMin sunpyValidateMin = field.getAnnotation(SunpyValidateMin.class);
            // 判断该字段是否为字符串
            if (sunpyValidateString != null && field.getType().equals(String.class)) {
                if (field.get(t) == null || ((String)field.get(t)).length() <= 0) {
                    System.out.println(field.getName() + "不可以为空!");
                    return false;
                }
            }
            
            if ((sunpyValidateMax != null || sunpyValidateMin != null)
                    && field.getType().equals(Integer.class)
                    && field.get(t) == null) {
                System.out.println(field.getName() + "字段不可以为空!");
                return false;
            }
            
            // 判断该字段是否为Integer或者int类型
            if (field.getType().equals(Integer.class)
                    || field.getType() == int.class) {
                if (sunpyValidateMax != null && ((int) field.get(t)) > sunpyValidateMax.max()) {
                    System.out.println(field.getName() + "字段大于了最大值!");
                    return false;
                }
                
                if (sunpyValidateMin != null && ((int) field.get(t)) < sunpyValidateMin.min()) {
                    System.out.println(field.getName() + "字段小于了最小值!");
                    return false;
                }
            }
        }
        
        return true;
    }
}

测试:

public class MyTest {

    public static void main(String[] args) throws Exception {
        User user = new User();
        user.setUsername("sunpy");
        user.setAge(150);
        System.out.println(ValidatorResolver.validate(user));
    }
}

结果:

age字段大于了最大值!
false

Java注解的本质

注解本质上就是一个接口,该接口默认继承Annotation接口。
image

posted @ 2025-04-27 17:49  sunpeiyu  阅读(16)  评论(0)    收藏  举报