Say I have an enum which is just
假设我有一个enum
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?
我想找到一个字符串的enum值,例如“a”将是blah - a。怎么可能这样做呢?
Is the Enum.valueOf()
the method I need? If so, how would I use this?
枚举. valueof()是我需要的方法吗?如果是的话,我怎么用这个呢?
23 个解决方案
#1
1830
Yes, Blah.valueOf("A")
will give you Blah.A
.
是的,Blah.valueOf(“A”)会给你Blah.A。
Note that the name must be an exact match, including case: Blah.valueOf("a")
and Blah.valueOf("A ")
both throw an IllegalArgumentException
.
注意,名称必须是精确匹配的,包括case: Blah. valueof(“a”)和Blah。valueOf(“A”)都抛出一个非法争论的异常。
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.ModalityType
shows both methods.
静态方法valueOf()和values()是在编译时创建的,不会出现在源代码中。不过,它们确实出现在Javadoc中;例如,对话框。ModalityType显示了这两种方法。
#2
700
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;
}
}
#3
95
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:
然后在我的enum类中,我通常都会保存一些输入:
public static MyEnum fromString(String name) {
return getEnumFromString(MyEnum.class, name);
}
If your enums are not all caps, just change the Enum.valueOf
line.
如果您的枚举不是全部的大写,那么只需更改Enum。返回对象的值。
Too bad I can't use T.class
for Enum.valueOf
as T
is erased.
可惜我不能用T。Enum类。当T的值被擦掉。
#4
65
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 toUpperCase
to toUpperCase(Locale.ENGLISH)
based on tc. comment and the java docs
基于tc编辑将toUpperCase更改为toUpperCase(Locale.ENGLISH)。注释和java文档
edit2 On android you should use Locale.US
, as sulai points out.
在android上应该使用Locale。苏莱指出,是美国。
#5
36
Use the pattern from Joshua Bloch, Effective Java:
使用Joshua Bloch的模式,有效Java:
(simplified for brevity)
(简洁简化)
enum MyEnum {
ENUM_1("A"),
ENUM_2("B");
private String name;
private static final Map<String,MyEnum> ENUM_MAP;
MyEnum (String name) {
this.name = name;
}
public String getName() {
return this.name;
}
// Build an immutable map of String name to enum pairs.
// Any Map impl can be used.
static {
Map<String,MyEnum> map = new ConcurrentHashMap<String,MyEnum>();
for (MyEnum instance : MyEnum.values()) {
map.put(instance.getName(),instance);
}
ENUM_MAP = Collections.unmodifiableMap(map);
}
public static MyEnum get (String name) {
return ENUM_MAP.get(name);
}
}
Also see:
还看到:
Oracle Java Example using Enum and Map of instances
使用Enum和实例映射的Oracle Java示例
Execution order of of static blocks in an Enum type
枚举类型中的静态块的执行顺序
How can I lookup a Java enum from its String value
如何从字符串值查找Java enum ?
#6
34
Here's a method that can do it for any Enum, and is case insensitive.
这里有一个方法可以对任何枚举执行此操作,并且不区分大小写。
/**
* 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()
));
}
#7
27
Using Blah.valueOf(string)
is best but you can use Enum.valueOf(Blah.class, string)
as well.
使用Blah. valueof (string)是最好的,但是可以使用Enum.valueOf(Blah)。类,字符串)。
#8
21
If you don't want to write your own utility use Google's guava library:
如果您不想编写自己的实用程序,请使用谷歌的番石榴库:
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函数不同,它让我们检查A是否在Blah中,并且不会抛出异常。
#9
13
You may need to this :
你可能需要这样:
public enum ObjectType {
PERSON("Person");
public String parameterName;
ObjectType(String parameterName) {
this.parameterName = parameterName;
}
public String getParameterName() {
return this.parameterName;
}
//From String method will return you the Enum for the provided input string
public static ObjectType fromString(String parameterName) {
if (parameterName != null) {
for (ObjectType objType : ObjectType.values()) {
if (parameterName.equalsIgnoreCase(objType.parameterName)) {
return objType;
}
}
}
return null;
}
}
One More Addition :
一个补充:
public static String fromEnumName(String parameterName) {
if (parameterName != null) {
for (DQJ objType : DQJ.values()) {
if (parameterName.equalsIgnoreCase(objType.name())) {
return objType.parameterName;
}
}
}
return null;
}
This will return you the Value by a Stringified Enum Name For e.g. if you provide "PERSON" in the fromEnumName it'll return you the Value of Enum i.e. "Person"
这将以一个Stringified Enum的名称返回值,例如,如果您在fromEnumName中提供“PERSON”,它将返回Enum的值。“人”
#10
11
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:
另一种方法是使用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");
}
}
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个示例
#11
8
My 2 cents here: using Java8 Streams + checking an exact string:
这里的2美分:使用Java8 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));
}
}
** EDIT **
* *编辑* *
Renamed the function to fromString()
since naming it using that convention, you'll obtain some benefits from Java language itself; for example:
将函数重命名为fromString(),因为使用该约定对其进行命名,您将从Java语言本身获得一些好处;例如:
- Direct conversion of types at HeaderParam annotation
- 在HeaderParam注释中直接转换类型
#12
8
In Java 8 or later, using Streams:
在Java 8或更高版本中,使用流:
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 fromText(String text) {
return Arrays.stream(values())
.filter(bl -> bl.text.equalsIgnoreCase(text))
.findFirst()
.orElse(null);
}
}
#13
6
Solution using Guava libraries. Method getPlanet () is case insensitive, so getPlanet ("MerCUrY") will return Planet.MERCURY.
解决方案使用番石榴库。方法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();
}
}
#14
6
To add to the previous answers, and address some of the discussions around nulls and NPE I'm using Guava Optionals to handle absent/invalid cases. This works great for URI/parameter parsing.
为了增加之前的答案,并解决一些关于nulls和NPE的讨论,我正在使用番石榴选项来处理缺席/无效的情况。这对于URI/参数解析非常有用。
public enum E {
A,B,C;
public static Optional<E> fromString(String s) {
try {
return Optional.of(E.valueOf(s.toUpperCase()));
} catch (IllegalArgumentException|NullPointerException e) {
return Optional.absent();
}
}
}
For those not aware, here's some more info on avoiding null with Optional: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional
对于那些不知道的人,这里有一些关于使用可选方法避免null的更多信息:https://code.google.com/p/guava- libraries/wiki/usingandavoidingnullexplence# Optional
#15
5
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;
}
#16
4
O(1) method inspired from thrift generated code which utilize a hashmap.
O(1)方法灵感来自于thrift生成的使用hashmap的代码。
public enum USER {
STUDENT("jon",0),TEACHER("tom",1);
private static final Map<String, Integer> map = new HashMap<>();
static {
for (USER user : EnumSet.allOf(USER.class)) {
map.put(user.getTypeName(), user.getIndex());
}
}
public static int findIndexByTypeName(String typeName) {
return map.get(typeName);
}
private USER(String typeName,int index){
this.typeName = typeName;
this.index = index;
}
private String typeName;
private int index;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
#17
4
In Java 8 the static Map pattern is even easier and is my preffered method. If you want to use the Enum with Jackson you can override toString and use that instead of name, then annotate with @JsonValue
在Java 8中,静态映射模式甚至更简单,并且是我的preffered方法。如果想使用Jackson的Enum,可以重写toString并使用它而不是name,然后使用@JsonValue注释
public enum MyEnum {
BAR,
BAZ;
private static final Map<String, MyEnum> MAP = Stream.of(MyEnum.values()).collect(Collectors.toMap(Enum::name, Function.identity()));
public static MyEnum fromName(String name){
return MAP.get(name);
}
}
public enum MyEnumForJson {
BAR("bar"),
BAZ("baz");
private static final Map<String, MyEnumForJson> MAP = Stream.of(MyEnumForJson.values()).collect(Collectors.toMap(Object::toString, Function.identity()));
private final String value;
MyEnumForJson(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return value;
}
public static MyEnumForJson fromValue(String value){
return MAP.get(value);
}
}
#18
3
java.lang.Enum
defines several useful methods, which is available to all enumeration type in Java:
. lang。Enum定义了一些有用的方法,Java中的所有枚举类型都可以使用这些方法:
- You can use
name()
method to get name of any Enum constants. String literal used to write enum constants is their name. - 可以使用name()方法获取任何Enum常量的名称。用于写入enum常量的字符串文本是它们的名称。
- Similarly
values()
method can be used to get an array of all Enum constants from an Enum type. - 类似地,可以使用values()方法从Enum类型获取所有Enum常量的数组。
- And for the asked question, you can use
valueOf()
method to convert any String to Enum constant in Java, as shown below. - 对于所问的问题,您可以使用valueOf()方法将Java中的任何字符串转换为Enum常量,如下所示。
public class EnumDemo06 {
public static void main(String args[]) {
Gender fromString = Gender.valueOf("MALE");
System.out.println("Gender.MALE.name() : " + fromString.name());
}
private enum Gender {
MALE, FEMALE;
}
}
Output:
Gender.MALE.name() : MALE
In this code snippet, valueOf()
method returns an Enum constant Gender.MALE, calling name on that returns "MALE"
.
在这个代码片段中,valueOf()方法返回Enum常量性别。男性,在上面呼唤名字返回“男性”。
#19
2
Apache's commons-lang library has a static function org.apache.commons.lang3.EnumUtils.getEnum which will map a String to your Enum type. Same answer essentially as Geoffreys but why roll your own when it's out there in the wild already.
Apache的common -lang库有一个静态函数org. Apache .common .lang3. enumutils . getenum,它将字符串映射到枚举类型。基本上和杰弗里斯的答案一样,但是为什么你自己的答案已经在野外了呢?
#20
2
Adding on to the top rated answer, with a helpful utility...
添加到最高评级的答案,与一个有用的实用工具…
valueOf()
throws two different Exceptions in cases where it doesn't like its input.
valueOf()在不喜欢输入的情况下抛出两个不同的异常。
IllegalArgumentException
- IllegalArgumentException
NullPointerExeption
- NullPointerExeption
If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...
如果您的需求是这样的,您不能保证您的字符串一定会匹配enum值,例如,如果字符串数据来自数据库,并且可能包含enum的旧版本,那么您将需要经常处理这些……
So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.
这是我写的一个可重用的方法,如果我们传递的字符串不匹配,它允许我们定义一个默认的Enum。
private static <T extends Enum<T>> T valueOf( String name , T defaultVal) {
try {
return Enum.valueOf(defaultVal.getDeclaringClass() , name);
} catch (IllegalArgumentException | NullPointerException e) {
return defaultVal;
}
}
Use it like this:
使用它是这样的:
public enum MYTHINGS {
THINGONE,
THINGTWO
}
public static void main(String [] asd) {
valueOf("THINGTWO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGTWO
valueOf("THINGZERO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGONE
}
#21
1
Another utility capturing in reverse way. Using a value which identify that Enum, not from its name.
另一个以相反方式捕获的实用程序。使用一个值来标识枚举,而不是从它的名称。
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.EnumSet;
public class EnumUtil {
/**
* Returns the <code>Enum</code> of type <code>enumType</code> whose a
* public method return value of this Enum is
* equal to <code>valor</code>.<br/>
* Such method should be unique public, not final and static method
* declared in Enum.
* In case of more than one method in match those conditions
* its first one will be chosen.
*
* @param enumType
* @param value
* @return
*/
public static <E extends Enum<E>> E from(Class<E> enumType, Object value) {
String methodName = getMethodIdentifier(enumType);
return from(enumType, value, methodName);
}
/**
* Returns the <code>Enum</code> of type <code>enumType</code> whose
* public method <code>methodName</code> return is
* equal to <code>value</code>.<br/>
*
* @param enumType
* @param value
* @param methodName
* @return
*/
public static <E extends Enum<E>> E from(Class<E> enumType, Object value, String methodName) {
EnumSet<E> enumSet = EnumSet.allOf(enumType);
for (E en : enumSet) {
try {
String invoke = enumType.getMethod(methodName).invoke(en).toString();
if (invoke.equals(value.toString())) {
return en;
}
} catch (Exception e) {
return null;
}
}
return null;
}
private static String getMethodIdentifier(Class<?> enumType) {
Method[] methods = enumType.getDeclaredMethods();
String name = null;
for (Method method : methods) {
int mod = method.getModifiers();
if (Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
name = method.getName();
break;
}
}
return name;
}
}
Example:
例子:
public enum Foo {
ONE("eins"), TWO("zwei"), THREE("drei");
private String value;
private Foo(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
EnumUtil.from(Foo.class, "drei")
returns Foo.THREE
, because it will use getValue
to match "drei", which is unique public, not final and not static method in Foo. In case Foo has more than on public, not final and not static method, for example, getTranslate
which returns "drei", the other method can be used: EnumUtil.from(Foo.class, "drei", "getTranslate")
.
EnumUtil.from(Foo.class drei)返回Foo。第三,因为它将使用getValue匹配“drei”,这是唯一的公共,而不是Foo中的final,也不是静态方法。如果Foo有多于on public,而不是final,也不是静态方法,例如getTranslate返回“drei”,那么可以使用另一个方法:EnumUtil.from(Foo.class,“drei”,“getTranslate”)。
#22
1
What about?
关于什么?
public enum MyEnum {
FIRST,
SECOND,
THIRD;
public static Optional<MyEnum> fromString(String value){
try{
return Optional.of(MyEnum.valueOf(value));
}catch(Exception e){
return Optional.empty();
}
}
}
#23
0
I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.
我喜欢使用这种方法将命令作为字符串解析成枚举。我通常将其中的一个枚举设置为“unknown”,因此在没有找到其他枚举时(即使在不区分大小写的情况下)返回该枚举,而不是null(即不存在值),这是有帮助的。因此我使用这种方法。
static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
Enum<E> unknown=null;
for (Enum<E> enumVal: enumClass.getEnumConstants()) {
if (what.compareToIgnoreCase(enumVal.name()) == 0) {
return enumVal;
}
if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
unknown=enumVal;
}
}
return unknown;
}
#1
1830
Yes, Blah.valueOf("A")
will give you Blah.A
.
是的,Blah.valueOf(“A”)会给你Blah.A。
Note that the name must be an exact match, including case: Blah.valueOf("a")
and Blah.valueOf("A ")
both throw an IllegalArgumentException
.
注意,名称必须是精确匹配的,包括case: Blah. valueof(“a”)和Blah。valueOf(“A”)都抛出一个非法争论的异常。
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.ModalityType
shows both methods.
静态方法valueOf()和values()是在编译时创建的,不会出现在源代码中。不过,它们确实出现在Javadoc中;例如,对话框。ModalityType显示了这两种方法。
#2
700
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;
}
}
#3
95
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:
然后在我的enum类中,我通常都会保存一些输入:
public static MyEnum fromString(String name) {
return getEnumFromString(MyEnum.class, name);
}
If your enums are not all caps, just change the Enum.valueOf
line.
如果您的枚举不是全部的大写,那么只需更改Enum。返回对象的值。
Too bad I can't use T.class
for Enum.valueOf
as T
is erased.
可惜我不能用T。Enum类。当T的值被擦掉。
#4
65
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 toUpperCase
to toUpperCase(Locale.ENGLISH)
based on tc. comment and the java docs
基于tc编辑将toUpperCase更改为toUpperCase(Locale.ENGLISH)。注释和java文档
edit2 On android you should use Locale.US
, as sulai points out.
在android上应该使用Locale。苏莱指出,是美国。
#5
36
Use the pattern from Joshua Bloch, Effective Java:
使用Joshua Bloch的模式,有效Java:
(simplified for brevity)
(简洁简化)
enum MyEnum {
ENUM_1("A"),
ENUM_2("B");
private String name;
private static final Map<String,MyEnum> ENUM_MAP;
MyEnum (String name) {
this.name = name;
}
public String getName() {
return this.name;
}
// Build an immutable map of String name to enum pairs.
// Any Map impl can be used.
static {
Map<String,MyEnum> map = new ConcurrentHashMap<String,MyEnum>();
for (MyEnum instance : MyEnum.values()) {
map.put(instance.getName(),instance);
}
ENUM_MAP = Collections.unmodifiableMap(map);
}
public static MyEnum get (String name) {
return ENUM_MAP.get(name);
}
}
Also see:
还看到:
Oracle Java Example using Enum and Map of instances
使用Enum和实例映射的Oracle Java示例
Execution order of of static blocks in an Enum type
枚举类型中的静态块的执行顺序
How can I lookup a Java enum from its String value
如何从字符串值查找Java enum ?
#6
34
Here's a method that can do it for any Enum, and is case insensitive.
这里有一个方法可以对任何枚举执行此操作,并且不区分大小写。
/**
* 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()
));
}
#7
27
Using Blah.valueOf(string)
is best but you can use Enum.valueOf(Blah.class, string)
as well.
使用Blah. valueof (string)是最好的,但是可以使用Enum.valueOf(Blah)。类,字符串)。
#8
21
If you don't want to write your own utility use Google's guava library:
如果您不想编写自己的实用程序,请使用谷歌的番石榴库:
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函数不同,它让我们检查A是否在Blah中,并且不会抛出异常。
#9
13
You may need to this :
你可能需要这样:
public enum ObjectType {
PERSON("Person");
public String parameterName;
ObjectType(String parameterName) {
this.parameterName = parameterName;
}
public String getParameterName() {
return this.parameterName;
}
//From String method will return you the Enum for the provided input string
public static ObjectType fromString(String parameterName) {
if (parameterName != null) {
for (ObjectType objType : ObjectType.values()) {
if (parameterName.equalsIgnoreCase(objType.parameterName)) {
return objType;
}
}
}
return null;
}
}
One More Addition :
一个补充:
public static String fromEnumName(String parameterName) {
if (parameterName != null) {
for (DQJ objType : DQJ.values()) {
if (parameterName.equalsIgnoreCase(objType.name())) {
return objType.parameterName;
}
}
}
return null;
}
This will return you the Value by a Stringified Enum Name For e.g. if you provide "PERSON" in the fromEnumName it'll return you the Value of Enum i.e. "Person"
这将以一个Stringified Enum的名称返回值,例如,如果您在fromEnumName中提供“PERSON”,它将返回Enum的值。“人”
#10
11
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:
另一种方法是使用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");
}
}
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个示例
#11
8
My 2 cents here: using Java8 Streams + checking an exact string:
这里的2美分:使用Java8 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));
}
}
** EDIT **
* *编辑* *
Renamed the function to fromString()
since naming it using that convention, you'll obtain some benefits from Java language itself; for example:
将函数重命名为fromString(),因为使用该约定对其进行命名,您将从Java语言本身获得一些好处;例如:
- Direct conversion of types at HeaderParam annotation
- 在HeaderParam注释中直接转换类型
#12
8
In Java 8 or later, using Streams:
在Java 8或更高版本中,使用流:
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 fromText(String text) {
return Arrays.stream(values())
.filter(bl -> bl.text.equalsIgnoreCase(text))
.findFirst()
.orElse(null);
}
}
#13
6
Solution using Guava libraries. Method getPlanet () is case insensitive, so getPlanet ("MerCUrY") will return Planet.MERCURY.
解决方案使用番石榴库。方法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();
}
}
#14
6
To add to the previous answers, and address some of the discussions around nulls and NPE I'm using Guava Optionals to handle absent/invalid cases. This works great for URI/parameter parsing.
为了增加之前的答案,并解决一些关于nulls和NPE的讨论,我正在使用番石榴选项来处理缺席/无效的情况。这对于URI/参数解析非常有用。
public enum E {
A,B,C;
public static Optional<E> fromString(String s) {
try {
return Optional.of(E.valueOf(s.toUpperCase()));
} catch (IllegalArgumentException|NullPointerException e) {
return Optional.absent();
}
}
}
For those not aware, here's some more info on avoiding null with Optional: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional
对于那些不知道的人,这里有一些关于使用可选方法避免null的更多信息:https://code.google.com/p/guava- libraries/wiki/usingandavoidingnullexplence# Optional
#15
5
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;
}
#16
4
O(1) method inspired from thrift generated code which utilize a hashmap.
O(1)方法灵感来自于thrift生成的使用hashmap的代码。
public enum USER {
STUDENT("jon",0),TEACHER("tom",1);
private static final Map<String, Integer> map = new HashMap<>();
static {
for (USER user : EnumSet.allOf(USER.class)) {
map.put(user.getTypeName(), user.getIndex());
}
}
public static int findIndexByTypeName(String typeName) {
return map.get(typeName);
}
private USER(String typeName,int index){
this.typeName = typeName;
this.index = index;
}
private String typeName;
private int index;
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
#17
4
In Java 8 the static Map pattern is even easier and is my preffered method. If you want to use the Enum with Jackson you can override toString and use that instead of name, then annotate with @JsonValue
在Java 8中,静态映射模式甚至更简单,并且是我的preffered方法。如果想使用Jackson的Enum,可以重写toString并使用它而不是name,然后使用@JsonValue注释
public enum MyEnum {
BAR,
BAZ;
private static final Map<String, MyEnum> MAP = Stream.of(MyEnum.values()).collect(Collectors.toMap(Enum::name, Function.identity()));
public static MyEnum fromName(String name){
return MAP.get(name);
}
}
public enum MyEnumForJson {
BAR("bar"),
BAZ("baz");
private static final Map<String, MyEnumForJson> MAP = Stream.of(MyEnumForJson.values()).collect(Collectors.toMap(Object::toString, Function.identity()));
private final String value;
MyEnumForJson(String value) {
this.value = value;
}
@JsonValue
@Override
public String toString() {
return value;
}
public static MyEnumForJson fromValue(String value){
return MAP.get(value);
}
}
#18
3
java.lang.Enum
defines several useful methods, which is available to all enumeration type in Java:
. lang。Enum定义了一些有用的方法,Java中的所有枚举类型都可以使用这些方法:
- You can use
name()
method to get name of any Enum constants. String literal used to write enum constants is their name. - 可以使用name()方法获取任何Enum常量的名称。用于写入enum常量的字符串文本是它们的名称。
- Similarly
values()
method can be used to get an array of all Enum constants from an Enum type. - 类似地,可以使用values()方法从Enum类型获取所有Enum常量的数组。
- And for the asked question, you can use
valueOf()
method to convert any String to Enum constant in Java, as shown below. - 对于所问的问题,您可以使用valueOf()方法将Java中的任何字符串转换为Enum常量,如下所示。
public class EnumDemo06 {
public static void main(String args[]) {
Gender fromString = Gender.valueOf("MALE");
System.out.println("Gender.MALE.name() : " + fromString.name());
}
private enum Gender {
MALE, FEMALE;
}
}
Output:
Gender.MALE.name() : MALE
In this code snippet, valueOf()
method returns an Enum constant Gender.MALE, calling name on that returns "MALE"
.
在这个代码片段中,valueOf()方法返回Enum常量性别。男性,在上面呼唤名字返回“男性”。
#19
2
Apache's commons-lang library has a static function org.apache.commons.lang3.EnumUtils.getEnum which will map a String to your Enum type. Same answer essentially as Geoffreys but why roll your own when it's out there in the wild already.
Apache的common -lang库有一个静态函数org. Apache .common .lang3. enumutils . getenum,它将字符串映射到枚举类型。基本上和杰弗里斯的答案一样,但是为什么你自己的答案已经在野外了呢?
#20
2
Adding on to the top rated answer, with a helpful utility...
添加到最高评级的答案,与一个有用的实用工具…
valueOf()
throws two different Exceptions in cases where it doesn't like its input.
valueOf()在不喜欢输入的情况下抛出两个不同的异常。
IllegalArgumentException
- IllegalArgumentException
NullPointerExeption
- NullPointerExeption
If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...
如果您的需求是这样的,您不能保证您的字符串一定会匹配enum值,例如,如果字符串数据来自数据库,并且可能包含enum的旧版本,那么您将需要经常处理这些……
So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.
这是我写的一个可重用的方法,如果我们传递的字符串不匹配,它允许我们定义一个默认的Enum。
private static <T extends Enum<T>> T valueOf( String name , T defaultVal) {
try {
return Enum.valueOf(defaultVal.getDeclaringClass() , name);
} catch (IllegalArgumentException | NullPointerException e) {
return defaultVal;
}
}
Use it like this:
使用它是这样的:
public enum MYTHINGS {
THINGONE,
THINGTWO
}
public static void main(String [] asd) {
valueOf("THINGTWO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGTWO
valueOf("THINGZERO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGONE
}
#21
1
Another utility capturing in reverse way. Using a value which identify that Enum, not from its name.
另一个以相反方式捕获的实用程序。使用一个值来标识枚举,而不是从它的名称。
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.EnumSet;
public class EnumUtil {
/**
* Returns the <code>Enum</code> of type <code>enumType</code> whose a
* public method return value of this Enum is
* equal to <code>valor</code>.<br/>
* Such method should be unique public, not final and static method
* declared in Enum.
* In case of more than one method in match those conditions
* its first one will be chosen.
*
* @param enumType
* @param value
* @return
*/
public static <E extends Enum<E>> E from(Class<E> enumType, Object value) {
String methodName = getMethodIdentifier(enumType);
return from(enumType, value, methodName);
}
/**
* Returns the <code>Enum</code> of type <code>enumType</code> whose
* public method <code>methodName</code> return is
* equal to <code>value</code>.<br/>
*
* @param enumType
* @param value
* @param methodName
* @return
*/
public static <E extends Enum<E>> E from(Class<E> enumType, Object value, String methodName) {
EnumSet<E> enumSet = EnumSet.allOf(enumType);
for (E en : enumSet) {
try {
String invoke = enumType.getMethod(methodName).invoke(en).toString();
if (invoke.equals(value.toString())) {
return en;
}
} catch (Exception e) {
return null;
}
}
return null;
}
private static String getMethodIdentifier(Class<?> enumType) {
Method[] methods = enumType.getDeclaredMethods();
String name = null;
for (Method method : methods) {
int mod = method.getModifiers();
if (Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
name = method.getName();
break;
}
}
return name;
}
}
Example:
例子:
public enum Foo {
ONE("eins"), TWO("zwei"), THREE("drei");
private String value;
private Foo(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
EnumUtil.from(Foo.class, "drei")
returns Foo.THREE
, because it will use getValue
to match "drei", which is unique public, not final and not static method in Foo. In case Foo has more than on public, not final and not static method, for example, getTranslate
which returns "drei", the other method can be used: EnumUtil.from(Foo.class, "drei", "getTranslate")
.
EnumUtil.from(Foo.class drei)返回Foo。第三,因为它将使用getValue匹配“drei”,这是唯一的公共,而不是Foo中的final,也不是静态方法。如果Foo有多于on public,而不是final,也不是静态方法,例如getTranslate返回“drei”,那么可以使用另一个方法:EnumUtil.from(Foo.class,“drei”,“getTranslate”)。
#22
1
What about?
关于什么?
public enum MyEnum {
FIRST,
SECOND,
THIRD;
public static Optional<MyEnum> fromString(String value){
try{
return Optional.of(MyEnum.valueOf(value));
}catch(Exception e){
return Optional.empty();
}
}
}
#23
0
I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.
我喜欢使用这种方法将命令作为字符串解析成枚举。我通常将其中的一个枚举设置为“unknown”,因此在没有找到其他枚举时(即使在不区分大小写的情况下)返回该枚举,而不是null(即不存在值),这是有帮助的。因此我使用这种方法。
static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
Enum<E> unknown=null;
for (Enum<E> enumVal: enumClass.getEnumConstants()) {
if (what.compareToIgnoreCase(enumVal.name()) == 0) {
return enumVal;
}
if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
unknown=enumVal;
}
}
return unknown;
}