假设我有一个枚举

public enum Blah {
    A, B, C, D
}

我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?

Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?


当前回答

Apache的commons-lang库有一个静态函数org.Apache.mons.lang3.EnumUtils.getEnum,它将字符串映射到Enum类型。基本上与杰弗里·郑的答案相同,但当它已经在野外时,不需要自己动手。

其他回答

Apache的commons-lang库有一个静态函数org.Apache.mons.lang3.EnumUtils.getEnum,它将字符串映射到Enum类型。基本上与杰弗里·郑的答案相同,但当它已经在野外时,不需要自己动手。

最好使用Blah.valueOf(字符串),但也可以使用Enum.valueOf(Blah.class,字符串)。

我的两分钱在这里:使用Java 8 Streams并检查精确的字符串:

public enum MyEnum {
    VALUE_1("Super"),
    VALUE_2("Rainbow"),
    VALUE_3("Dash"),
    VALUE_3("Rocks");

    private final String value;

    MyEnum(String value) {
        this.value = value;
    }

    /**
     * @return the Enum representation for the given string.
     * @throws IllegalArgumentException if unknown string.
     */
    public static MyEnum fromString(String s) throws IllegalArgumentException {
        return Arrays.stream(MyEnum.values())
                .filter(v -> v.value.equals(s))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
    }
}

我将函数重命名为fromString(),因为使用该约定命名它,您将从Java语言本身获得一些好处;例如:

在HeaderParam注释处直接转换类型

另一种实现方法是使用Enum的隐式静态方法name()。name将返回用于创建枚举的确切字符串,该枚举可用于对照提供的字符串进行检查:

public enum Blah {

    A, B, C, D;

    public static Blah getEnum(String s){
        if(A.name().equals(s)){
            return A;
        }else if(B.name().equals(s)){
            return B;
        }else if(C.name().equals(s)){
            return C;
        }else if (D.name().equals(s)){
            return D;
        }
        throw new IllegalArgumentException("No Enum specified for this string");
    }
}

测试:

System.out.println(Blah.getEnum("B").name());


// It will print B  B

灵感:Java中Enum的10个示例

public static MyEnum getFromValue(String value) {
    MyEnum resp = null;
    MyEnum nodes[] = values();
    for(int i = 0; i < nodes.length; i++) {
        if(nodes[i].value.equals(value)) {
            resp = nodes[i];
            break;
        }
    }
    return resp;
}