Java – how to convert an object to an enumeration to use it in a switch statement
Using java 8, I have a map. I need to convert it to another map to replace the key name and sometimes the value For example, when they become enumerations, I need to convert these enumerations to other constants (strings, sometimes integers) I don't want to compare strings, the enum Name(), because there may be duplicates, but I prefer to convert object to enumeration and open it However, I can't find a method to convert object to switchable enumeration Enum. Valueof does not return switchable content (see the example below)
private void put(String key,Object value) {
if (value != null && value.getClass().isEnum()) {
Enum<?> val = (Enum<?>)value;
/* The below line has the following problem:
* Cannot switch on a value of type Enum.
* Only convertible int values,strings or enum variables are
* permitted */
switch (Enum.valueOf(val.getClass(),val.name())) {
case EmploymentType.FULL_TIME_EMPLOYEE : value = "Fast anställd";
break;
case ResidenceType.TENANCY : value = "Hyresrätt";
break;
default : break;
}
}
map.put(key,value);
}
I know I can:
private void put(String key,Object value) {
if (value != null && value.getClass().isEnum()) {
if (value.equals(EmploymentType.FULL_TIME_EMPLOYEE) value = "Fast anställd";
else if (value.equals(ResidenceType.TENANCY) value = "Hyresrätt";
}
map.put(key,value);
}
But I found it not so elegant and as easy to read as a switch statement Is there any way to do this?
Solution
It seems that you have to deal with multiple enumeration types But you can't switch multiple enumeration types in a switch statement I think you can use map < < enum , Object > instead
You can set up a HashMap like this:
Map<Enum<?>,Object> enumMap = new HashMap<>(); enumMap.put(EmploymentType.FULL_TIME_EMPLOYEE,"Fast anställd"); enumMap.put(ResidenceType.TENANCY,"Hyresrätt");
And use it like this:
if (enumMap.containsKey(value)) {
value = enumMap.get(value);
}
map.put(key,value);
