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.
An enum is a special class that represents a group of constants. To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. values() method can be used to return all values present inside enum.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Enum contastants are static and final by default and cannot be changed after once it is created. Also Enums can be used in Switch statements like int and char data types. We can define values for enum constants at the time of creation, but then we must add a constructor and a field variable for this enum.
Java Enums. The Enum in Java is a data type which contains a fixed set of constants.
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"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With