如何使用 id 检索 Enum 名称? [英] How to retrieve Enum name using the id?
问题描述
我有 enum
为:
public enum EnumStatus {
PASSED(40L, "Has Passed"),
AVERAGE(60L, "Has Average Marks"),
GOOD(80L, "Has Good Marks");
private java.lang.String name;
private java.lang.Long id;
EnumStatus(Long id, java.lang.String name) {
this.name = name;
this.id = id;
}
public java.lang.String getName() {
return name;
}
public java.lang.Long getId() {
return id;
}
}
我必须仅使用 id(40,60, 80)获取枚举名称(PASSED
、AVERAGE
、GOOD
).我该怎么做?
I have to get the Enum names(PASSED
, AVERAGE
, GOOD
) using the ids only(40,60, 80). How do I do it?
推荐答案
在您的 enum
中创建一个静态方法,该方法在 values
中搜索(隐式方法/成员,不要t 确切知道它是哪个)并返回相应的值.对于方法找不到匹配值的情况,您应该创建一个特殊条目,例如UNKNOWN
,您可以返回.这样,您就不必返回 null
,这总是一个坏主意.
Create a static method in your enum
which searches in values
(implicit method/member, don't know exactly which is it) and returns the corresponding value. For cases in which the method can not find a matching value, you should create a special entry, e.g. UNKNOWN
, which you can return. This way, you do not have to return null
, which is always a bad idea.
public static EnumStatus getById(Long id) {
for(EnumStatus e : values()) {
if(e.id.equals(id)) return e;
}
return UNKNOWN;
}
顺便说一句 - 你的代码似乎是错误的.GOOD
后面的括号似乎不属于那里.
Btw - your code seems to be wrong. The bracket after GOOD
seems to not belong there.
这篇关于如何使用 id 检索 Enum 名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!