Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 717
jilt3d Avatar asked May 12 '14 12:05

jilt3d


People also ask

How do you declare a constant in an enum in Java?

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.

Can Java enum be static?

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).

Can we add constants to enum?

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.

Does enum contain fixed set of constants?

Java Enums. The Enum in Java is a data type which contains a fixed set of constants.


1 Answers

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";     } } 
like image 168
Maciej Dobrowolski Avatar answered Sep 22 '22 06:09

Maciej Dobrowolski