如何使用“描述”找出Java Enum的“名称”

时间:2013-03-04 08:41:11

标签: java enums

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

3 个答案:

答案 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;

    }