【发布时间】:2011-11-08 10:42:57
【问题描述】:
我有如下界面
public interface DeviceKey {
String getKey();
}
我还有各种扩展这个接口的枚举。
在一个包含所有枚举的类中,我想要一个基于字符串(键)的方法,可以返回该字符串对应的枚举。该字符串与枚举相关,但不是名称。我的类和枚举可能如下所示:
public class Settings {
private static final Map<String, DeviceKey> lookupAll = Maps.newHashMap();
static {
lookupAll.putAll(SmartSetting.lookup);
// Plus a lot more similar to these
}
public static DeviceKey valueOfAnyKey(String key) {
return lookupAll.get(key);
}
public enum SmartSetting implements DeviceKey {
STATUS("smart_status");
private static final Map<String, SmartSetting> lookup = EnumUtil.addAll(SmartSetting.class);
private final String key;
SmartEncryptionSetting(String key) {
this.key = key;
}
@Override
public String getKey() {
return key;
}
}
}
valueOfAnyKey() 的当前实现返回当然不是枚举的 DeviceKey。我应该怎么做才能让valueOfAnyKey() 返回一个 DeviceKey 类型的枚举?
EnumUtil:
private static class EnumUtil {
public static <T extends Enum<T> & DeviceKey> Map<String, T> addAll(Class<T> theClass) {
final Map<String, T> retval = new HashMap<String, T>();
for(T s : EnumSet.allOf(theClass)) {
retval.put(s.getKey(), s);
}
return retval;
}
}
【问题讨论】:
标签: java generics interface enums enumeration