全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-11 6 分钟 ✍️ juanwangdev

Java元注解

元注解是修饰注解的注解,用于定义注解的行为和作用范围。

五种元注解

元注解作用
@Retention定义注解保留策略
@Target定义注解适用目标
@Inherited允许子类继承注解
@Documented注解包含在JavaDoc中
@Repeatable允许注解重复使用

@Retention - 保留策略

Java
// 源码保留:编译后丢弃,用于编译检查
@Retention(RetentionPolicy.SOURCE)
public @interface Override {}

// 类文件保留:记录在class文件,运行时不可见(默认)
@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation {}

// 运行时保留:可通过反射读取
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
    String name();
}

@Target - 适用目标

Java
// 可作用于类、接口、枚举
@Target(ElementType.TYPE)
public @interface Table {}

// 可作用于字段
@Target(ElementType.FIELD)
public @interface Column {}

// 可作用于方法
@Target(ElementType.METHOD)
public @interface Getter {}

// 多目标
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {}

// 所有类型注解(Java 8+)
@Target(ElementType.TYPE_USE)
public @interface MyTypeAnnotation {}

ElementType枚举值

目标
TYPE类、接口、枚举
FIELD字段
METHOD方法
PARAMETER参数
CONSTRUCTOR构造器
LOCAL_VARIABLE局部变量
ANNOTATION_TYPE注解类型
PACKAGE
TYPE_PARAMETER类型参数(Java 8)
TYPE_USE类型使用(Java 8)

@Inherited - 继承

Java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface MyAnnotation {}

// 使用注解
@MyAnnotation
public class Parent {}

// 子类自动继承@MyAnnotation
public class Child extends Parent {}

验证继承:

Java
Class<Child> clazz = Child.class;
MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);
// annotation不为null,说明继承了父类的注解

@Documented - 文档化

Java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface ApiDoc {
    String value();
}

// 使用@ApiDoc的方法在生成JavaDoc时会包含该注解

@Repeatable - 可重复(Java 8+)

Java
// 定义容器注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Roles {
    Role[] value();
}

// 定义可重复注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Roles.class)
public @interface Role {
    String name();
}

// 使用:可以重复标注
@Role(name = "admin")
@Role(name = "user")
@Role(name = "guest")
public class User {}

// 反射获取
Role[] roles = User.class.getAnnotationsByType(Role.class);
Roles rolesContainer = User.class.getAnnotation(Roles.class);

元注解组合示例

Java
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@Documented
public @interface ApiMapping {
    String value() default "";
    String method() default "GET";
    String[] headers() default {};
}

注意事项

@Inherited 只对类继承有效,接口继承无效

不指定 @Target 时,注解可用于任何位置

不指定 @Retention 时,默认为 CLASS 策略

@Repeatable 要求容器注解的 value 成员必须是原注解数组类型

要点总结

  1. @Retention 定义注解生命周期:SOURCE、CLASS、RUNTIME
  2. @Target 定义注解可修饰的程序元素
  3. @Inherited 允许子类继承父类的类注解
  4. @Documented 使注解出现在JavaDoc中
  5. @Repeatable 允许同一位置重复使用同一注解

📝 发现内容有误?点击此处直接编辑

← 上一篇 Java Class对象获取
下一篇 → Java反射机制概述
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库