简体   繁体   English

如何在 Java 枚举中定义静态常量?

[英]How to define static constants in a Java enum?

Is there any way to define static final variables (effectively constants) in a Java enum declaration?有没有办法在 Java 枚举声明中定义静态最终变量(实际上是常量)?

What I want is to define in one place the string literal value for the BAR(1...n) values:我想要的是在一个地方定义 BAR(1...n) 值的字符串文字值:

@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 .对于上面的代码,我收到以下错误消息:无法在定义之前引用字段

As IntelliJ IDEA suggest when extracting constant - make static nested class.正如 IntelliJ IDEA 在提取常量时所建议的那样 - 制作静态嵌套类。 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";
    }
}
public enum MyEnum {
    BAR1(MyEnum.BAR_VALUE);

    public static final String BAR_VALUE = "Bar";

works fine工作正常

public enum MyEnum {
//  BAR1(       foo),   // error: illegal forward reference
//  BAR2(MyEnum.foo2),  // error: illegal forward reference
    BAR3(MyEnum.foo);   // no error

  public static final int foo =0;
  public static       int foo2=0;
  MyEnum(int i) {}

  public static void main(String[] args) { System.out.println("ok");}
}

This can be done without an inner class for the constant.这可以在没有常量的内部类的情况下完成。

Maybe you should considering breaking this enum into two fields: an enum and an int:也许你应该考虑把这个枚举分成两个字段:一个枚举和一个整数:

@RequiredArgsConstructor
public enum MyEnum {
    BAR("Bar"),
    FOO("Foo")

    @Getter
    private final String value;
}

And then use:然后使用:

private MyEnum type;
private int value;

(You can put that into a class or not, whether it makes sense to you) (你可以把它放到一个类中,不管它对你有意义)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM