共計 536 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中的枚舉類是不能直接添加屬性的,因為枚舉常量是有限且預定義的,不支持實例化和自定義屬性。不過,可以通過在枚舉常量中定義屬性值來達到類似的效果。以下是解決方法:
- 在枚舉常量中定義屬性值:
public enum MyEnum {CONSTANT1("Value1"),
CONSTANT2("Value2"),
CONSTANT3("Value3");
private final String value;
private MyEnum(String value) {this.value = value;}
public String getValue() {return value;}
}
- 在枚舉類中定義一個方法來獲取屬性值:
public enum MyEnum {
CONSTANT1,
CONSTANT2,
CONSTANT3;
public String getValue() {switch (this) {
case CONSTANT1:
return "Value1";
case CONSTANT2:
return "Value2";
case CONSTANT3:
return "Value3";
default:
return null;
}
}
}
這樣就可以在枚舉常量中添加屬性值,并通過方法來獲取屬性值了。
丸趣 TV 網 – 提供最優質的資源集合!
正文完