How to define static constants in a Java enum?

后端 未结 4 1615
-上瘾入骨i
-上瘾入骨i 2020-12-02 22:18

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

4条回答
  •  温柔的废话
    2020-12-02 22:43

    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";
        }
    }
    

提交回复
热议问题