public enum Test {
a("This is a"),
b("This is b"),
c("This is c"),
d("This is d");
private final String type;
Test(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
以上是我的简单代码。有人可以教我如何使用desc获取名称吗? 例如:我有一个字符串“这是c”,我想使用这个字符串来获取Test.c
答案 0 :(得分:4)
使用enum的values
方法,迭代它,你就可以得到它。
public enum Test {
a("This is a"),
b("This is b"),
c("This is c"),
d("This is d");
private final String type;
Test(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static Test getByDesc(String desc){
for(Test t : Test.values()){
if(t.getType().equals(desc)){
return t;
}
}
return null;
}
}
答案 1 :(得分:3)
假设你想经常这样做,你想要从类型(你在代码中没有任何名称为“description”的东西)到Test
建立一个地图。例如:
// Within Test
private static final Map<String, Test> typeMap = createTypeMap();
private static Map<String, Test> createTypeMap() {
Map<String, Test> ret = new HashMap<String, Test>();
for (Test test : Test.values()) {
ret.put(test.type, test);
}
return ret;
}
public static Test fromType(String type) {
return typeMap.get(type);
}
答案 2 :(得分:0)
此方法将根据enumvalue
返回枚举类型public static Test getEnum(String enumValue) {
for (Test c : Test.values()) {
if (c.getValue().equalsIgnoreCase(enumValue))
return c;
}
return null;
}