如何从 Java 中的字符串值中获取枚举值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/604424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:45:57  来源:igfitidea点击:

How to get an enum value from a string value in Java?

javaenums

提问by Malachi

Say I have an enum which is just

说我有一个枚举,它只是

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

and I would like to find the enum value of a string, for example "A"which would be Blah.A. How would it be possible to do this?

我想找到一个字符串的枚举值,例如"A"哪个是Blah.A. 怎么可能做到这一点?

Is the Enum.valueOf()the method I need? If so, how would I use this?

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

采纳答案by Michael Myers

Yes, Blah.valueOf("A")will give you Blah.A.

是的,Blah.valueOf("A")会给你Blah.A

Note that the name must be an exactmatch, including case: Blah.valueOf("a")and Blah.valueOf("A ")both throw an IllegalArgumentException.

请注意,名称必须完全匹配,包括 case:Blah.valueOf("a")并且Blah.valueOf("A ")都抛出IllegalArgumentException.

The static methods valueOf()and values()are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityTypeshows both methods.

静态方法valueOf()values()是在编译时创建的,不会出现在源代码中。不过,它们确实出现在 Javadoc 中;例如,Dialog.ModalityType显示了这两种方法。

回答by Jo?o Portela

You should also be careful with your case. Let me explain: doing Blah.valueOf("A")works, but Blah.valueOf("a")will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH))would work.

你也应该小心你的情况。让我解释一下:做Blah.valueOf("A")工作,但Blah.valueOf("a")不会工作。然后再Blah.valueOf("a".toUpperCase(Locale.ENGLISH))工作。

edit
Changed toUpperCaseto toUpperCase(Locale.ENGLISH)based on tc. commentand the java docs

编辑
更改toUpperCasetoUpperCase(Locale.ENGLISH)基于tc。评论java 文档

edit2On android you should use Locale.US, as sulai points out.

edit2在 android 上你应该使用Locale.US,正如sulai 指出的那样

回答by Peter Lawrey

Using Blah.valueOf(string)is best but you can use Enum.valueOf(Blah.class, string)as well.

使用Blah.valueOf(string)是最好的,但您也可以使用Enum.valueOf(Blah.class, string)

回答by Geoffrey Zheng

Here's a nifty utility I use:

这是我使用的一个漂亮的实用程序:

/**
 * A common method for all enums since they can't have another base class
 * @param <T> Enum type
 * @param c enum type. All enums must be all caps.
 * @param string case insensitive
 * @return corresponding enum, or null
 */
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
    if( c != null && string != null ) {
        try {
            return Enum.valueOf(c, string.trim().toUpperCase());
        } catch(IllegalArgumentException ex) {
        }
    }
    return null;
}

Then in my enum class I usually have this to save some typing:

然后在我的枚举类中,我通常使用它来保存一些输入:

public static MyEnum fromString(String name) {
    return getEnumFromString(MyEnum.class, name);
}

If your enums are not all caps, just change the Enum.valueOfline.

如果您的枚举不是全部大写,只需更改该Enum.valueOf行。

Too bad I can't use T.classfor Enum.valueOfas Tis erased.

太糟糕了,我不能使用T.classEnum.valueOf因为T它被擦除了。

回答by JoséMi

Another solution if the text is not the same to the enumeration value:

如果文本与枚举值不同,另一种解决方案:

public enum Blah {
    A("text1"),
    B("text2"),
    C("text3"),
    D("text4");

    private String text;

    Blah(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

    public static Blah fromString(String text) {
        for (Blah b : Blah.values()) {
            if (b.text.equalsIgnoreCase(text)) {
                return b;
            }
        }
        return null;
    }
}

回答by Prasobh.Kollattu

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;
}

回答by Vikram

Another way of doing this by using implicit static method name()of Enum. name will return the exact string used to create that enum which can be used to check against provided string:

另一种方法是使用name()Enum 的隐式静态方法。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");
    }
}

Testing:

测试:

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

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

//it will print B  B

inspiration: 10 Examples of Enum in Java

灵感:Java 中的 10 个枚举示例

回答by Patrick Arnesen

Here's a method that can do it for any Enum, and is case insensitive.

这是一种可以对任何 Enum 执行此操作的方法,并且不区分大小写。

/** 
 * Finds the value of the given enumeration by name, case-insensitive. 
 * Throws an IllegalArgumentException if no match is found.  
 **/
public static <T extends Enum<T>> T valueOfIgnoreCase(
        Class<T> enumeration, String name) {

    for (T enumValue : enumeration.getEnumConstants()) {
        if (enumValue.name().equalsIgnoreCase(name)) {
            return enumValue;
        }
    }

    throw new IllegalArgumentException(String.format(
        "There is no value with name '%s' in Enum %s",
        name, enumeration.getName()
    ));
}

回答by Andrejs

If you don't want to write your own utility use Google's guavalibrary:

如果您不想编写自己的实用程序,请使用 Google 的番石榴库:

Enums.getIfPresent(Blah.class, "A")

Unlike the built in java function it let's you check if A is present in Blah and doesn't throw an exception.

与内置的 java 函数不同,它让您检查 Blah 中是否存在 A 并且不会引发异常。

回答by javabrew

Solution using Guava libraries. Method getPlanet () is case insensitive, so getPlanet ("MerCUrY") will return Planet.MERCURY.

使用 Guava 库的解决方案。方法 getPlanet () 不区分大小写,因此 getPlanet ("MerCUrY") 将返回 Planet.MERCURY。

package com.universe.solarsystem.planets;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Enums;
import com.google.common.base.Optional;

//Pluto and Eris are dwarf planets, who cares!
public enum Planet {
   MERCURY,
   VENUS,
   EARTH,
   MARS,
   JUPITER,
   SATURN,
   URANUS,
   NEPTUNE;

   public static Planet getPlanet(String name) {
      String val = StringUtils.trimToEmpty(name).toUpperCase();
      Optional <Planet> possible = Enums.getIfPresent(Planet.class, val);
      if (!possible.isPresent()) {
         throw new IllegalArgumentException(val + "? There is no such planet!");
      }
      return possible.get();
   }
}