我能否使用Java将String
转换为等价的Enumeration
值?
当然,我可以使用大量的if-else
语句来实现,但如果可能的话,我想避免这样做。
根据这份文档:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html
我对此没有太多希望,在不使用if
或case
语句的情况下实现转换可能性不大。
我能否使用Java将String
转换为等价的Enumeration
值?
当然,我可以使用大量的if-else
语句来实现,但如果可能的话,我想避免这样做。
根据这份文档:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html
我对此没有太多希望,在不使用if
或case
语句的情况下实现转换可能性不大。
希望你意识到,java.util.Enumeration
和Java 1.5的枚举类型是不同的。
你可以使用YourEnum.valueOf("String")
来获取相应的枚举类型。
因此,如果你的枚举类型定义如下:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
你可以这样做:String day = "SUNDAY";
Day dayEnum = Day.valueOf(day);
假设您使用的是Java 5枚举(这不是很确定,因为您提到旧的Enumeration
类),则可以使用java.lang.Enum
子类的valueOf
方法:
MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");
使用每个enum
定义的静态方法valueOf(String)
。
例如,如果您有enum MyEnum
,则可以使用MyEnum.valueOf("foo")
我可能过度工程化了自己的解决方案,没有意识到Type.valueOf("enum string")
实际上存在。
我猜它提供了更细粒度的控制,但我不确定它是否真的有必要。
public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
IllegalArgumentException
替换为 RuntimeException
(或者任何你想要抛出的异常),这样有可能可以简化代码。Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}
// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
// Consider using trim to eliminate extraneous whitespace
enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (Exception e) {
// handle the situation here. Here are a couple of ideas.
// Apply null and expect the using code to detect.
enumValue = null;
// Have a defined private constant for a default value
// assuming a default value would make more sense than null
enumValue = DEFAULT_BEST_ENUM_EVER;
}
但你也可以以独特的方式处理每个异常。
Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}
// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
// Consider using trim to eliminate extraneous whitespace
enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (IllegalArgumentException e1) {
// handle the situation here ...
} catch (NullPointerException e2) {
// handle the situation here ...
}