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

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等
StringString name();
ClassClass 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 元注解让子类继承

要点总结

  1. 注解用 @interface 关键字定义
  2. 成员类型受限:基本类型、String、Class、枚举、注解及它们的数组
  3. 三种保留策略:SOURCE、CLASS、RUNTIME
  4. 默认值用 default 指定,不能为 null
  5. 单成员 value 可省略名称

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

← 上一篇 Java注解处理器
下一篇 → Java编译时注解
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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