java枚举比较大小写,字符串与Java枚举的不区分大小写的匹配

Java provides a valueOf() method for every Enum object, so given an enum like

public enum Day {

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

}

one can do a lookup like

Day day = Day.valueOf("Monday");

If the string passed to valueOf() does not match (case sensitive) an existing Day value, an IllegalArgumentException is thrown.

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;

}

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 class at compile time?

The signature of such a "generic" lookup() method would be similar to the Enum.valueOf() method, i.e.:

public static > T lookup(Class enumType, String name);

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 searchEnum(Class enumeration,

String search) {

for (T each : enumeration.getEnumConstants()) {

if (each.name().compareToIgnoreCase(search) == 0) {

return each;

}

}

return null;

}

Example

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"));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值