@Repeatable 是干嘛的
时间: 2023-11-21 12:50:59 浏览: 34
@Repeatable 是 Java 8 中新增的注解,用于标识某个注解可以重复使用。在 Java 8 之前,一个元素只能使用一次某个注解,如果需要使用多个相同的注解,则需要将这些注解放在一个容器中,然后将容器作为元素的注解。而使用 @Repeatable 注解后,可以直接在元素上使用相同的注解,使代码更加简洁易懂。
下面是一个使用 @Repeatable 注解的示例:
```java
@Repeatable(Fruits.class)
@interface Fruit {
String name() default "";
String color() default "";
}
@interface Fruits {
Fruit[] value();
}
@Fruit(name = "apple", color = "red")
@Fruit(name = "banana", color = "yellow")
public class FruitTest {
public static void main(String[] args) {
Fruit[] fruits = FruitTest.class.getAnnotationsByType(Fruit.class);
for (Fruit fruit : fruits) {
System.out.println(fruit.name() + " is " + fruit.color());
}
}
}
```
在上面的示例中,@Fruit 注解使用了 @Repeatable(Fruits.class),表示 @Fruit 注解可以重复使用,并且容器注解为 @Fruits。在 FruitTest 类中,我们同时使用了两个 @Fruit 注解,表示这个类既是苹果又是香蕉。在 main 方法中,我们通过 getAnnotationsByType 方法获取了 FruitTest 类上的所有 @Fruit 注解,并遍历输出了每个水果的名称和颜色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)