Java 8 Repeating Annotations

本文最后更新于 2024年4月15日 下午

Introduction

Java 8 引入了可重复注解 @Repeatable 的功能,允许相同的注解可以在同一个元素上多次使用。

In Practice

定义可重复注解及其容器注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.lang.annotation.*;

// 定义可重复注解
@Repeatable(Authors.class) // 传入容器注解作为参数
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Author {
String name();
}

// 定义容器注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Authors {
Author[] value();
}

在类上使用可重复注解

1
2
3
4
5
@Author(name = "John")
@Author(name = "Doe")
public class Book {
// 类的内容...
}

获取可重复注解的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.lang.annotation.Annotation;

public class Main {
public static void main(String[] args) {
// 获取类上的 Authors 注解,这里需要获取容器注解 Authors 而不是 Author 注解
Authors authors = Book.class.getAnnotation(Authors.class);
// 获取 Authors 注解中的所有 Author 注解
Author[] authorArray = authors.value();
// 遍历 Author 注解,获取 name 属性值
for (Author author : authorArray) {
System.out.println("Author: " + author.name());
}
}
}

Java 8 Repeating Annotations
https://stein283036.github.io/2024/04/15/Java-8-Repeating-Annotations/
作者
倪京龙
发布于
2024年4月15日
更新于
2024年4月15日
许可协议