温馨提示×

温馨提示×

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

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

如何自定义java注解

发布时间:2026-10-22 22:05:05 来源:亿速云 阅读:83 作者:小樊 栏目:编程语言

在 Java 中,自定义注解(Annotation)主要用于为代码提供元数据,常与反射、编译期处理或框架结合使用。下面从基本定义 → 元注解 → 成员变量 → 使用方式 → 运行时读取逐步说明。


一、定义一个最简单的注解

public @interface MyAnnotation {
}

使用:

@MyAnnotation
public class Test {
}

二、使用元注解(非常重要)

Java 提供了 4 个元注解来控制注解的行为:

1️⃣ @Target —— 注解能用在哪里

@Target(ElementType.METHOD)

常见取值:

  • TYPE(类、接口)
  • METHOD(方法)
  • FIELD(字段)
  • PARAMETER(参数)
  • CONSTRUCTOR
  • LOCAL_VARIABLE

示例:

@Target({ElementType.METHOD, ElementType.FIELD})

2️⃣ @Retention —— 注解保留到什么时候

@Retention(RetentionPolicy.RUNTIME)

三种策略:

  • SOURCE:仅存在于源码(编译后丢弃)
  • CLASS:保留到 .class 文件(默认)
  • RUNTIME:运行时可用(最常用,可反射读取)

3️⃣ @Documented —— 是否生成到 JavaDoc

@Documented

4️⃣ @Inherited —— 子类是否继承注解

@Inherited

只对类有效,不对方法、字段有效。


三、带参数的注解(成员变量)

注解中的“变量”其实是方法形式:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
    int count() default 1;
}

使用:

@MyAnnotation(value = "hello", count = 3)
public void test() {
}

如果只有一个 value(),可省略名字:

@MyAnnotation("hello")

四、运行时读取注解(反射)

Method method = Test.class.getMethod("test");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);

if (annotation != null) {
    System.out.println(annotation.value());
    System.out.println(annotation.count());
}

五、完整示例

自定义注解

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

使用

public class Service {
    @Log("查询用户")
    public void query() {}
}

读取

for (Method m : Service.class.getMethods()) {
    if (m.isAnnotationPresent(Log.class)) {
        Log log = m.getAnnotation(Log.class);
        System.out.println(m.getName() + " -> " + log.value());
    }
}

六、常见使用场景

  • 权限校验(@RequiresPermission)
  • 日志记录
  • 接口限流
  • 参数校验(如 Hibernate Validator)
  • Spring / MyBatis 等框架核心机制

如果你需要:

  • ✅ 编译期注解(APT)
  • ✅ Spring 中的自定义注解
  • ✅ 结合 AOP 使用

可以告诉我具体方向,我可以进一步举例。

向AI问一下细节

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

AI
助
手