@Retention(RetentionPolicy.RUNTIME) 表示注解保留在运行的时候有效
@Target(ElementType.TYPE) 表示注解作用对象是类,FIELD是字段,METHOD是方法........

反射知识点
Java反射

注解

类注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface TestAnnotation_Class{
String TableName();
}

字段注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface TestAnnotation_Field{
    String type();
    String value();
    String dbTableName();
}

测试注解(至少为了下方方便区别,也是类注解)

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface tests{
    String test();
}

反射搭配注解的使用

比如有以下测试类剩余注解
 @tests(test="测试注解")
@TestAnnotation_Class(TableName="t_user")
class TestClass{
    @TestAnnotation_Field(type="id",value="1001",dbTableName="t_user")
    private String id;
    @TestAnnotation_Field(type="name",value="张三",dbTableName="t_user")
    private String name;
    @TestAnnotation_Field(type="age",value="18",dbTableName="t_user")
    private int age;

}

反射获取注解的信息
如注解在类

通过 Class class1=TestClass.class;获取类,然后根据这个类获取全部注解列表class1.getAnnotations();
public class T8 {
    public static void main(String[] args) {
        Class class1=TestClass.class;
        Annotation[] annotations=class1.getAnnotations();
        for(Annotation annotation:annotations){
            System.out.println(annotation);
        }
    }
}

得到结果
2025-10-01T10:05:06.png

如果想要获取指定注解,那么如下

通过class1.getAnnotation(注解类对象);来获取
2025-10-01T10:06:49.png
2025-10-01T10:07:35.png

得到注解以后,强转获取里面的属性
2025-10-01T10:12:33.png

如注解在字段
2025-10-01T10:15:08.png
比如外卖要获取id的注解,并且获取注解的属性

先获取这个类对象,再通过类获取指定字段 Field field=class1.getDeclaredField("id");
,再通过字段获取注解 TestAnnotation_Field field1_an=field.getAnnotation(TestAnnotation_Field.class);
然后获取注解的属性如下

2025-10-01T10:18:13.png