How to define static constants in a Java enum?

后端 未结 4 1605
-上瘾入骨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:30

    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)

    0 讨论(0)
  • 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";
        }
    }
    
    0 讨论(0)
  • 2020-12-02 22:46
    public enum MyEnum {
        BAR1(MyEnum.BAR_VALUE);
    
        public static final String BAR_VALUE = "Bar";
    

    works fine

    0 讨论(0)
  • 2020-12-02 22:46
    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.

    0 讨论(0)
提交回复
热议问题