温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java注解如何定义

发布时间:2026-09-11 19:12:35 来源:亿速云 阅读:85 作者:小樊 栏目:编程语言

在 Java 中,注解(Annotation)是通过 @interface 关键字来定义的。下面从基本定义、元注解、成员变量、使用示例几个方面说明。


一、最基础的注解定义

public @interface MyAnnotation {
}

使用方式:

@MyAnnotation
public class Test {
}

二、带属性的注解(成员变量)

注解中的“属性”其实是抽象方法,但写法像变量。

public @interface MyAnnotation {
    String value();
    int count() default 1;
}

使用:

@MyAnnotation(value = "hello", count = 3)
public class Test {
}

如果只有一个 value 属性,可以省略名称:

@MyAnnotation("hello")

三、元注解(用于修饰注解)

Java 提供了 5 个常用元注解:

1. @Target

指定注解可以用在哪里(类、方法、字段等)

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
public @interface MyAnnotation {
}

常见取值:

  • TYPE:类、接口
  • METHOD:方法
  • FIELD:字段
  • PARAMETER:参数
  • CONSTRUCTOR:构造方法

2. @Retention

指定注解的生命周期

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

取值:

  • SOURCE:源码阶段(如 @Override
  • CLASS:字节码阶段(默认)
  • RUNTIME:运行时(可通过反射读取)✅ 最常用

3. @Documented

注解是否包含在 JavaDoc 中

@Documented
public @interface MyAnnotation {
}

4. @Inherited

子类是否继承父类的注解

@Inherited
public @interface MyAnnotation {
}

5. @Repeatable(Java 8+)

允许注解重复使用

@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
    String value();
}

public @interface MyAnnotations {
    MyAnnotation[] value();
}

使用:

@MyAnnotation("a")
@MyAnnotation("b")
public class Test {
}

四、完整示例

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    String value() default "";
}

使用 + 反射读取:

public class Test {

    @Log("测试方法")
    public void test() {}

    public static void main(String[] args) throws Exception {
        Method m = Test.class.getMethod("test");
        if (m.isAnnotationPresent(Log.class)) {
            Log log = m.getAnnotation(Log.class);
            System.out.println(log.value());
        }
    }
}

五、小结

  • @interface 定义注解
  • 属性像方法,可设默认值
  • 用元注解控制作用范围和生命周期
  • RUNTIME + 反射 才能读取注解

如果你是想了解Spring 注解 / 自定义校验注解 / 编译期注解,也可以继续问我。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI