public interface Identifiable<K> { K getId(); } public class EnumFactory { public static <T extends Enum<T> & Identifiable<K> , K > T getEnum(Class<T> type, K id) { for (T t : type.getEnumConstants()) { if(t.getId().equals(id)) { return t; } } return null; } public static <T extends Enum<T> & Identifiable<K> , K > T get(Class<T> type, K id) { EnumSet<T> set = EnumSet.allOf(type); if(set == null || set.size() <= 0){ return null; } for(T t: set){ if(t.getId().equals(id)){ return t; } } return null; } } public enum MonthEnum implements Identifiable<Integer>{ January(1), February(2), March(3), April(4), May(5), June(6); int value; private MonthEnum(int value){ this.value = value; } @Override public Integer getId() { return this.value; } } public enum WeekEnum implements Identifiable<String>{ Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; @Override public String getId() { return name(); } } public class Client { public static void main(String[] args) { WeekEnum we = EnumFactory.get(WeekEnum.class, "Monday"); System.out.println(we); MonthEnum me = EnumFactory.getEnum(MonthEnum.class, 4); System.out.println(me); } }
今天忽然发现个非常恶心的问题,enum有一个的方法叫valueOf,参数是String,但是在找不到String对应的enum的时候,竟然会直接抛异常出来:
反编译enum的class文件可以看到会添加一个valueOf的方法:
public static RuntimeSettingKey valueOf(String s) { return (RuntimeSettingKey)Enum.valueOf(test/RuntimeSettingKey, s); }实际是调用父类的valueOf:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) { T result = enumType.enumConstantDirectory().get(name); if (result != null) return result; if (name == null) throw new NullPointerException("Name is null"); throw new IllegalArgumentException( "No enum const " + enumType +"." + name); }我擦,为啥不能返回一个null呢?
这会导致调用valueOf的地方必须得加一个try-catch!另一种变通的做法是,自己来遍历,不用valueOf方法,二者都够恶心的,really ugly!