Is there any way to define static final variables (effectively constants) in a Java enum declaration?
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.
asked May 12, 2014 at 12:20
jilt3djilt3d4,05488 gold badges3636 silver badges4141 bronze badges
7As 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";
}
}
answered May 12, 2014 at 12:33
Maciej DobrowolskiMaciej Dobrowolski12.2k55 gold badges4949 silver badges7171 bronze badges
5public enum MyEnum {
BAR1(MyEnum.BAR_VALUE);
public static final String BAR_VALUE = "Bar";
works fine
shmosel51k77 gold badges8181 silver badges148148 bronze badges
answered Nov 29, 2019 at 11:10
ThomasMorusThomasMorus43744 silver badges22 bronze badges
9class Scratch {
public static void main(String[] args) {
System.out.println(MyEnum.BAR3); // 10:BAR3
}
}
enum MyEnum {
// BAR1( foo), // error: illegal forward reference
// BAR2(MyEnum.foo2), // error: illegal forward reference
BAR3(MyEnum.foo); // no error
int x;
public static final int foo =10;
public static int foo2=20;
MyEnum(int i) {x = i;}
@Override public String toString() { return x+":"+super.toString(); }
}
This can be done without an inner class for the constant. And field initialization works as expected (in case you don't know, it is possible to read static fields before they are initialized, you will read the default 0 or null, but it does not happen here).
answered Nov 30, 2019 at 8:36
ThomasMorusThomasMorus7111 silver badge11 bronze badge
Start asking to get answers
Find the answer to your question by asking.
Ask questionExplore related questions
See similar questions with these tags.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4