Java注解定义
注解(Annotation)为代码提供元数据,广泛应用于框架配置和代码生成。
注解定义语法
基本语法
Java
public @interface 注解名 {
// 成员声明
}
定义示例
Java
// 无成员注解(标记注解)
public @interface MyAnnotation {
}
// 带成员的注解
public @interface Author {
String name();
String date();
}
// 带默认值的注解
public @interface Schedule {
String time() default "09:00";
int priority() default 1;
}
注解成员规则
成员类型限制
注解成员只能是以下类型:
| 类型 | 示例 |
|---|---|
| 基本类型 | int, long, double, boolean等 |
| String | String name(); |
| Class | Class type(); |
| 枚举 | TimeUnit unit(); |
| 注解 | Author author(); |
| 以上类型的数组 | String[] tags(); |
成员声明示例
Java
public @interface FieldConfig {
// 基本类型
String name();
int length() default 255;
// Class类型
Class<?> type() default String.class;
// 枚举
FieldType fieldType() default FieldType.TEXT;
// 注解嵌套
Constraint constraint() default @Constraint(required = true);
// 数组
String[] tags() default {};
}
三种保留策略
使用 @Retention 元注解指定保留策略:
Java
// 源码保留(编译后丢弃)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
// 类文件保留(默认,运行时不可见)
@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation {
}
// 运行时保留(可通过反射读取)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
String name();
}
策略对比
| 策略 | 范围 | 典型用途 |
|---|---|---|
| SOURCE | 源码 | 编译检查(@Override, @SuppressWarnings) |
| CLASS | 字节码 | 字节码操作工具 |
| RUNTIME | 运行时 | 反射读取配置 |
注解使用示例
Java
// 定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
String name() default "";
String schema() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
String name() default "";
boolean nullable() default true;
int length() default 255;
}
// 使用注解
@Table(name = "t_user", schema = "app")
public class User {
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "username", length = 50)
private String username;
}
注解使用语法
Java
// 无成员
@MyAnnotation
public class MyClass {}
// 单成员(可省略value)
@Author("张三")
public class MyClass {}
// 多成员
@Author(name = "张三", date = "2024-01-01")
public class MyClass {}
// 数组成员
@Tags({"java", "reflection"})
public class MyClass {}
// 单元素数组可省略花括号
@Tags("java")
public class MyClass {}
注意事项
注解成员不能为 null,必须指定默认值或使用时赋值
若只有一个成员名为 value,使用时可省略成员名
注解成员的默认值必须是编译时常量
注解不能继承其他注解,但可以使用 @Inherited 元注解让子类继承
要点总结
- 注解用 @interface 关键字定义
- 成员类型受限:基本类型、String、Class、枚举、注解及它们的数组
- 三种保留策略:SOURCE、CLASS、RUNTIME
- 默认值用 default 指定,不能为 null
- 单成员 value 可省略名称
📝 发现内容有误?点击此处直接编辑