如何在 Java 枚举中定义静态常量? [英] How to define static constants in a Java enum?

查看:29
本文介绍了如何在 Java 枚举中定义静态常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Java 枚举声明中定义静态最终变量(实际上是常量)?

Is there any way to define static final variables (effectively constants) in a Java enum declaration?

我想要的是在一个地方定义 BAR(1...n) 值的字符串文字值:

What I want is to define in one place the string literal value for the BAR(1...n) values:

@RequiredArgsConstructor
public enum MyEnum {
    BAR1(BAR_VALUE),
    FOO("Foo"),
    BAR2(BAR_VALUE),
    ...,
    BARn(BAR_VALUE);

    private static final String BAR_VALUE = "Bar";

    @Getter
    private final String value;
}

对于上述代码,我收到以下错误消息:在定义字段之前无法引用字段.

I got the following error message for the code above: Cannot reference a field before it is defined.

推荐答案

正如 IntelliJ IDEA 在提取常量时所建议的 - 制作静态嵌套类.这种方法有效:

As IntelliJ IDEA suggest when extracting constant - make static nested class. This approach works:

@RequiredArgsConstructor
public enum MyEnum {
    BAR1(Constants.BAR_VALUE),
    FOO("Foo"),
    BAR2(Constants.BAR_VALUE),
    ...,
    BARn(Constants.BAR_VALUE);



    @Getter
    private final String value;

    private static class Constants {
        public static final String BAR_VALUE = "BAR";
    }
}

这篇关于如何在 Java 枚举中定义静态常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆