/*** 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;}
然后在我的枚举类中,我通常有这个来保存一些输入:
public static MyEnum fromString(String name) {return getEnumFromString(MyEnum.class, 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
/*** 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()));}
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();}}
public enum ObjectType {PERSON("Person");
public String parameterName;
ObjectType(String parameterName) {this.parameterName = parameterName;}
public String getParameterName() {return this.parameterName;}
// From the String method, it will return you the Enum for the provided input stringpublic static ObjectType fromString(String parameterName) {if (parameterName != null) {for (ObjectType objType : ObjectType.values()) {if (parameterName.equalsIgnoreCase(objType.parameterName)) {return objType;}}}return null;}}
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;}}
示例:
public enum Foo {ONE("eins"), TWO("zwei"), THREE("drei");
private String value;
private Foo(String value) {this.value = value;}
public String getValue() {return value;}}
public enum ToggleStatusUpdate {OFF("off", 1),ON("on", 2);
private final String name;private final int position;
private ToggleStatusUpdate(String name, int position) {this.name = name;this.position = position;}
public String getName() {return name;}
public int getPosition() {return position;}
public static int getPositionForName(String name) {for(ToggleStatusUpdate toggleStatusUpdate : ToggleStatusUpdate.values()) {if (toggleStatusUpdate.getName().equals(name)) {return toggleStatusUpdate.getPosition();}}return -1;}
public static void main(String[] args) {System.out.println(ToggleStatusUpdate.getPositionForName("off"));}}