Java基础回顾——注解

介绍

注解Annotation:是放在Java源码的类、方法、字段、参数前的一种特殊注释

注释会被编译器直接忽略,注解则可以被编译器打包进入class文件,因此,注解是一种用作标注的“元数据”。

作用
1、编译器使用的注解
不会被编译进入.class文件,在编译后就被编译器扔掉了

例子:

@Override:让编译器检查该方法是否正确地实现了覆写;
@SuppressWarnings:告诉编译器忽略此处代码产生的警告。

2、由工具处理.class文件使用的注解

3、在程序运行期能够读取的注解,它们在加载后一直存在于JVM中,这也是最常用的注解。

定义注解时,可以定义配置参数,可以有默认值。

public class Hello {
    @Check(min=0, max=100, value=55)
    public int n;

    @Check(value=99)
    public int p;

    @Check(99) // @Check(value=99)
    public int x;

    @Check
    public int y;
}

定义注解

使用@interface语法来定义注解(Annotation)

public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

元注解
作用:修饰其他注解。

Java中已经定义了一些元注解。

常用的:

1、@Target

使用@Target可以定义Annotation能够被应用于源码的哪些位置:

  • 类或接口:ElementType.TYPE;
  • 字段:ElementType.FIELD;
  • 方法:ElementType.METHOD;
  • 构造方法:ElementType.CONSTRUCTOR;
  • 方法参数:ElementType.PARAMETER。
@Target(ElementType.METHOD)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

@Target({
    ElementType.METHOD,
    ElementType.FIELD
})
public @interface Report {
    ...
}

2、@Retention

@Retention定义了Annotation的生命周期:

  • 仅编译期:RetentionPolicy.SOURCE;
  • 仅class文件:RetentionPolicy.CLASS;
  • 运行期:RetentionPolicy.RUNTIME。

如果@Retention不存在,则该Annotation默认为CLASS。

3、@Repeatable

@Repeatable可以定义Annotation是否可重复。

4、@Inherited
@Inherited定义子类是否可继承父类定义的Annotation。

@Inherited仅针对@Target(ElementType.TYPE)类型的annotation有效,并且仅针对class的继承,对interface的继承无效

@Inherited
@Target(ElementType.TYPE)
public @interface Report {
    int type() default 0;
    String level() default "info";
    String value() default "";
}

定义Annotation步骤:

1、用@interface定义注解

2、添加参数,默认值

3、用元注解配置注解

其中,必须设置@Target和@Retention,@Retention一般设置为RUNTIME

处理注解

根据@Retention的配置:

  • SOURCE类型的注解在编译期就被丢掉了;
  • CLASS类型的注解仅保存在class文件中,它们不会被加载进JVM;
  • RUNTIME类型的注解会被加载进JVM,并且在运行期可以被程序读取。

SOURCE类型的注解主要由编译器使用,一般只使用,不编写。CLASS类型的注解主要由底层工具库使用,涉及到class的加载,一般很少用到。只有RUNTIME类型的注解不但要使用,还经常需要编写。

读取RUNTIME类型注解

注解定义后也是一种class,所有的注解都继承自java.lang.annotation.Annotation,读取注解,需要使用反射API

Java提供的使用反射API读取Annotation的方法包括:

判断某个注解是否存在于Class、Field、Method或Constructor:

  • Class.isAnnotationPresent(Class)
  • Field.isAnnotationPresent(Class)
  • Method.isAnnotationPresent(Class)
  • Constructor.isAnnotationPresent(Class)

使用反射API读取Annotation:

  • Class.getAnnotation(Class)
  • Field.getAnnotation(Class)
  • Method.getAnnotation(Class)
  • Constructor.getAnnotation(Class)

使用反射API读取Annotation有两种方法。方法一是先判断Annotation是否存在,如果存在,就直接读取:

Class cls = Person.class;
if (cls.isAnnotationPresent(Report.class)) {
    Report report = cls.getAnnotation(Report.class);
    ...
}

第二种方法是直接读取Annotation,如果Annotation不存在,将返回null:

Class cls = Person.class;
Report report = cls.getAnnotation(Report.class);
if (report != null) {
   ...
}

要读取方法参数的注解,我们先用反射获取Method实例,然后读取方法参数的所有注解:

public void hello(@NotNull @Range(max=5) String name, @NotNull String prefix) {
}

// 获取Method实例:
Method m = ...
// 获取所有参数的Annotation:
Annotation[][] annos = m.getParameterAnnotations();
// 第一个参数(索引为0)的所有Annotation:
Annotation[] annosOfName = annos[0];
for (Annotation anno : annosOfName) {
    if (anno instanceof Range r) { // @Range注解
        r.max();
    }
    if (anno instanceof NotNull n) { // @NotNull注解
        //
    }
}

使用注解

例子:

写一个@Range注解,希望用它来定义一个String字段的规则:字段长度满足@Range的参数定义:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
    int min() default 0;
    int max() default 255;
}

在某个JavaBean中,可以使用该注解:

public class Person {
    @Range(min=1, max=20)
    public String name;

    @Range(max=10)
    public String city;
}

但是,定义了注解,本身对程序逻辑没有任何影响。必须自己编写代码来使用注解。这里,编写一个Person实例的检查方法,它可以检查Person实例的String字段长度是否满足@Range的定义:

void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
    // 遍历所有Field:
    for (Field field : person.getClass().getFields()) {
        // 获取Field定义的@Range:
        Range range = field.getAnnotation(Range.class);
        // 如果@Range存在:
        if (range != null) {
            // 获取Field的值:
            Object value = field.get(person);
            // 如果值是String:
            if (value instanceof String s) {
                // 判断值是否满足@Range的min/max:
                if (s.length() < range.min() || s.length() > range.max()) {
                    throw new IllegalArgumentException("Invalid field: " + field.getName());
                }
            }
        }
    }
}

例子
只看不知道具体怎么写,就看着敲了一遍

Range.java

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
    int min() default 0;
    int max() default 255;
}

Animal.java

public class Animal {
    @Range(min = 2, max =20)
    public String name;

    @Range(min = 0, max =8)
    public int number;

    public Animal(String name,int number) {
        this.name = name;
        this.number = number;
    }
}

TestAnnotation2.java

import java.lang.reflect.Field;

public class TestAnnotation2 {
    public static void main(String[] args) throws ReflectiveOperationException {
        Animal animal=new Animal("1",10);
        check(animal);
    }

    static  void check(Animal person) throws IllegalArgumentException,ReflectiveOperationException{
        for(Field field : person.getClass().getFields()){
            Range range=field.getAnnotation(Range.class);
            if(range!=null){
                Object value=field.get(person);
                if(value instanceof String){
                    if (((String) value).length() < range.min() || ((String) value).length() > range.max()) {
                        System.out.println("Invalid field: " + field.getName());
                    }
                }

                if(value instanceof Integer){
                    if ((int)value < range.min() || (int)value > range.max()) {
                        System.out.println("Invalid field: " + field.getName());
                    }
                }
            }
        }
    }
}
  • 17
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值