java enums 如何配合注解使用

avatar
作者
筋斗云
阅读量:0

在 Java 中,可以通过在 enum 常量上使用注解来为每个枚举常量添加元数据信息。下面是一个简单的示例,展示了如何在 Java 中使用注解和枚举一起配合使用:

import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;  // 定义一个注解 @Retention(RetentionPolicy.RUNTIME) @interface Color {     String value(); }  // 定义一个枚举 enum Fruit {     @Color("Red")     APPLE,      @Color("Yellow")     BANANA,      @Color("Green")     PEAR }  public class EnumWithAnnotationExample {     public static void main(String[] args) {         // 遍历枚举常量,获取注解信息         for (Fruit fruit : Fruit.values()) {             Color colorAnnotation = fruit.getClass().getDeclaredField(fruit.name()).getAnnotation(Color.class);             System.out.println(fruit.name() + " is " + colorAnnotation.value());         }     } } 

在上面的示例中,我们定义了一个 Color 注解和一个 Fruit 枚举。每个枚举常量都使用 @Color 注解来指定颜色信息。然后,在 main 方法中,我们遍历枚举常量,获取每个常量上的注解信息,并打印出来。

运行上面的代码,输出结果为:

APPLE is Red BANANA is Yellow PEAR is Green 

通过这种方式,我们可以为枚举常量添加更多的元数据信息,并在程序中使用注解来获取这些信息。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!