I have the following interface
public interface DeviceKey {
String getKey();
}
I also have various enums that all extends this interface.
In a class that contains all the enums I want a method that based on a string (key), can return the enum corresponding to this string. The string is related to an enum, but it is not the name. My class and enum could look like this:
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;
}
}
}
The current implementation of valueOfAnyKey() returns DeviceKey which of course is not an enum. What should I do in order to make valueOfAnyKey() return an enum of the type DeviceKey?
The 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;
}
}
In Java a method can only return one type. You cannot have it return
DeviceKey“and”Enum