如何在 Java 枚举中定义静态常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23608885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define static constants in a Java enum?
提问by jilt3d
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.
对于上面的代码,我收到以下错误消息:无法在定义之前引用字段。
采纳答案by Maciej Dobrowolski
As IntelliJ IDEA suggest when extracting constant - make static nested class. This approach works:
正如 IntelliJ IDEA 在提取常量时所建议的那样 - 制作静态嵌套类。这种方法有效:
@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";
}
}
回答by Luan Nico
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)
(你可以把它放到一个类中,不管它对你有意义)
回答by ThomasMorus
public enum MyEnum {
BAR1(MyEnum.BAR_VALUE);
public static final String BAR_VALUE = "Bar";
works fine
工作正常
回答by ThomasMorus
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.
这可以在没有常量的内部类的情况下完成。