[英]How to define static constants in a Java enum?
有沒有辦法在 Java 枚舉聲明中定義靜態最終變量(實際上是常量)?
我想要的是在一個地方定義 BAR(1...n) 值的字符串文字值:
@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;
}
對於上面的代碼,我收到以下錯誤消息:無法在定義之前引用字段。
正如 IntelliJ IDEA 在提取常量時所建議的那樣 - 制作靜態嵌套類。 這種方法有效:
@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";
}
}
public enum MyEnum {
BAR1(MyEnum.BAR_VALUE);
public static final String BAR_VALUE = "Bar";
工作正常
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");}
}
這可以在沒有常量的內部類的情況下完成。
也許你應該考慮把這個枚舉分成兩個字段:一個枚舉和一個整數:
@RequiredArgsConstructor
public enum MyEnum {
BAR("Bar"),
FOO("Foo")
@Getter
private final String value;
}
然后使用:
private MyEnum type;
private int value;
(你可以把它放到一個類中,不管它對你有意義)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.