温馨提示×

java enums 如何配合注解使用

小樊
82
2024-08-05 22:13:15
栏目: 编程语言

在 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

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

0