我正在尝试在枚举中创建一个私有(private)静态最终变量,但我不断收到编译错误。有谁知道如何解决这个问题?
Multiple markers at this line
- Syntax error, insert "Identifier" to complete EnumConstantHeaderName
- Syntax error, insert "}" to complete EnumBody
class Foo {
...
public enum MyEnum {
private static final String MY_STRING = "a string I use in a constructor";
private static final String MY_OTHER_STRING = "a string I use in another constructor";
MyEnumType(1, MY_STRING),
MyEnumType2(2, MY_STRING),
MyEnumType3(3, MY_OTHER_STRING);
MyEnum(int num, String str) {
...
}
}
...
}
最佳答案
枚举常量需要是枚举中的第一个元素。可编译的代码版本:
class Foo {
public enum MyEnum {
MyEnumType, MyEnumType2;
public String bar() {
return MY_STRING;
}
public String bar2() {
return MY_STRING + "2";
}
private static final String MY_STRING = "a string I reuse in the enum";
}
}
* 编辑 *
根据您对原始问题所做的修改,我知道您要做什么。不,不可能在枚举定义本身中声明的枚举文字声明中使用常量。这是因为文字声明必须是枚举中的第一个元素。这是 Java 语言规范规定的。两件快速的事情:
- 您正在使用
private static final Strings
。这给你 绝对比使用字符串文字没有任何好处, 这将解决问题。 - 如果你想声明可重用的常量(
public static final Strings
) 那么你需要在枚举之外这样做。
或者,您可以将您的枚举声明为为您定义 private static final String
的类的嵌套元素。
一些伪代码:
public class Foo {
public static enum MyEnum {
MyEnumType(0, MY_STRING), MyEnumType2(1, "Hello");
private int ordinal;
private String value;
MyEnum(int ordinal, String value) {
this.ordinal = ordinal;
this.value = value;
}
public int getOrdinal() {
return ordinal;
}
public String getValue() {
return value;
}
public void setOrdinal(int ordinal) {
this.ordinal = ordinal;
}
public void setValue(String value) {
this.value = value;
}
}
private static final String MY_STRING = "a string I reuse in the enum";
}
关于java - 枚举中的私有(private)静态最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9270313/