How to define static constants in a Java enum?

后端 未结 4 1610
-上瘾入骨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)

提交回复
热议问题