字符串与Java枚举的不区分大小写的匹配 [英] Case-insensitive matching of a string to a Java enum
问题描述
Java
为每个枚举< T>提供
valueOf()
code> object,所以给出一个枚举
像
Java
provides a valueOf()
method for every Enum<T>
object, so given an enum
like
public enum Day {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
可以像
Day day = Day.valueOf("Monday");
如果字符串传递给 valueOf()
不匹配(区分大小写)现有的日
值,抛出 IllegalArgumentException
。
If the string passed to valueOf()
does not match (case sensitive) an existing Day
value, an IllegalArgumentException
is thrown.
要进行不区分大小写的匹配,可以在 Day
枚举中编写一个自定义方法,例如
To do a case-insensitive matching, one can write a custom method inside the Day
enum, e.g.
public static Day lookup(String day) {
for (Day d : Day.values()) {
if (d.name().equalsIgnoreCase(day)) {
return type;
}
}
return null;
}
有没有任何通用的方式,不使用值缓存或任何其他额外的对象,写一个静态的 lookup()
方法,如上所述一次(即不是每个枚举
),给定在编译时将 values()
方法隐式添加到 Enum< E>
类中?
Is there any generic way, without using caching of values or any other extra objects, to write a static lookup()
method like the above only once (i.e., not for every enum
), given that the values()
method is implicitly added to the Enum<E>
class at compile time?
这样一个通用 lookup()
方法的签名将类似于 Enum.valueOf ()
方法,即:
The signature of such a "generic" lookup()
method would be similar to the Enum.valueOf()
method, i.e.:
public static <T extends Enum<T>> T lookup(Class<T> enumType, String name);
,它将完全实现 Day.lookup()
方法为任何枚举
,而不需要为每个枚举重新编写相同的方法
and it would implement exactly the functionality of the Day.lookup()
method for any enum
, without the need to re-write the same method for each enum
.
推荐答案
我发现特殊混合的泛型有点棘手,但这有用。
I found getting the special blend of generics a little tricky, but this works.
public static <T extends Enum<?>> T searchEnum(Class<T> enumeration,
String search) {
for (T each : enumeration.getEnumConstants()) {
if (each.name().compareToIgnoreCase(search) == 0) {
return each;
}
}
return null;
}
示例
public enum Horse {
THREE_LEG_JOE, GLUE_FACTORY
};
public static void main(String[] args) {
System.out.println(searchEnum(Horse.class, "Three_Leg_Joe"));
System.out.println(searchEnum(Day.class, "ThUrSdAy"));
}
这篇关于字符串与Java枚举的不区分大小写的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!