我需要创建一个包含一些带有空格的字符串及其对应的int
值的Enum
,例如:
public enum status{
Active(1),
Inactive(2);
}
因为我将与 Hibernate 一起使用它,并且还将将其转换为 JSON 以供 Alpaca JS 表单使用。
例如:
[{"text": "Inactive", "value":"2"},{"text": "Active", "value":"1"}]
我制作enum
时卡住了。如何制作这种类型的enum
?
我需要创建一个包含一些带有空格的字符串及其对应的int
值的Enum
,例如:
public enum status{
Active(1),
Inactive(2);
}
因为我将与 Hibernate 一起使用它,并且还将将其转换为 JSON 以供 Alpaca JS 表单使用。
例如:
[{"text": "Inactive", "value":"2"},{"text": "Active", "value":"1"}]
我制作enum
时卡住了。如何制作这种类型的enum
?
您不能在字符串之间放置空格。您可以使用下划线来代替,如下所示:
In_Active
您可以使用这种方式:
enum Status {
ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);
private final String key;
private final Integer value;
Status(String key, Integer value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public Integer getValue() {
return value;
}
}
您可以在一个enum
中持有多个值,甚至可以使用getter来处理它们。以下是我曾经使用的一个示例(我尝试将其适应于您的问题):
您可以在一个enum
中持有多个值,甚至可以使用getter来处理它们。以下是我曾经使用的一个示例(我尝试将其适应于您的问题):
public enum Status{
ACTIVE(1, "Active"),
INACTIVE(2, "In Active");
private final Integer value;
private final String text;
/**
* A mapping between the integer code and its corresponding text to facilitate lookup by code.
*/
private static Map<Integer, Status> valueToTextMapping;
private Status(Integer value, String text){
this.value = value;
this.text = text;
}
public static Status getStatus(Integer i){
if(valueToTextMapping == null){
initMapping();
}
return valueToTextMapping.get(i);
}
private static void initMapping(){
valueToTextMapping = new HashMap<>();
for(Status s : values()){
valueToTextMapping.put(s.value, s);
}
}
public Integer getValue(){
return value;
}
public String getText(){
return text;
}
@Override
public String toString(){
final StringBuilder sb = new StringBuilder();
sb.append("Status");
sb.append("{value=").append(value);
sb.append(", text='").append(text).append('\'')
sb.append('}');
return sb.toString();
}
}
在您的代码中,您可以简单地使用 Status.ACTIVE
,它将表示一个您想要的包含value
和text
的枚举实例。
Status.ACTIVE.name()
和Status.ACTIVE.toString()
之间存在差异,并且在此实现中甚至包括Status.ACTIVE.getText()
。可能自动生成的代码调用了.name()
方法。在这种情况下,您应该更改并调用.getText()
或更改您的toString()
(更好)。 - GameDroids.toString()
方法将枚举转换为字符串 - 因此,您可能需要重写该方法。 - GameDroids在标识符中间不能加空格。
查看此链接是否可能在Java中为枚举分配数值?以在Java中为枚举分配值。