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 成员必须是原注解数组类型
要点总结
- @Retention 定义注解生命周期:SOURCE、CLASS、RUNTIME
- @Target 定义注解可修饰的程序元素
- @Inherited 允许子类继承父类的类注解
- @Documented 使注解出现在JavaDoc中
- @Repeatable 允许同一位置重复使用同一注解
📝 发现内容有误?点击此处直接编辑