Java注解的元注解有哪些?它们各自的作用是什么?

在 Java 中,元注解(Meta-Annotation)是用于定义其他注解的注解。Java 提供了五种元注解,分别是 @Retention、@Target、@Documented、@Inherited 和 @Repeatable。以下是它们的作用及详细说明:

  1. @Retention
    @Retention 用于指定注解的保留策略,即注解在什么阶段有效。它有三个可选值:

    • RetentionPolicy.SOURCE:注解仅在源代码中保留,编译时会被丢弃。
    • RetentionPolicy.CLASS:注解在编译时保留,但运行时不可见(默认值)。
    • RetentionPolicy.RUNTIME:注解在运行时保留,可以通过反射获取。

    示例:

    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation {
        String value() default "default";
    }
    
  2. @Target
    @Target 用于指定注解可以应用于哪些程序元素(如类、方法、字段等)。它通过 ElementType 枚举指定目标:

    • ElementType.TYPE:类、接口、枚举。
    • ElementType.FIELD:字段。
    • ElementType.METHOD:方法。
    • 其他如 PARAMETER、CONSTRUCTOR 等。

    示例:

    @Target({ElementType.METHOD, ElementType.TYPE})
    public @interface MyAnnotation {
        String value();
    }
    
  3. @Documented
    @Documented 表示注解会被包含在 Javadoc 中。默认情况下,注解不会被 Javadoc 记录。

    示例:

    @Documented
    public @interface MyAnnotation {
        String author() default "unknown";
    }
    
  4. @Inherited
    @Inherited 表示注解会被子类继承。如果父类使用了该注解,子类也默认继承该注解。

    示例:

    @Inherited
    public @interface MyAnnotation {
        String description();
    }
    
  5. @Repeatable
    @Repeatable(Java 8 引入)表示注解可以在同一个程序元素上多次使用。需要指定一个容器注解来存储重复的注解。

    示例:

    @Repeatable(Annotations.class)
    public @interface MyAnnotation {
        String value();
    }
    
    public @interface Annotations {
        MyAnnotation[] value();
    }
    

这些元注解是 Java 注解系统的核心,通过灵活组合它们可以设计出功能强大的自定义注解。