I have configuration files which can be populated with enums and their respective values and will then be read by my program.
For example, a configuration file (yaml format) may look like this:
SomeEnumClass:
- VALUE_A_OF_SOME_ENUM
- VALUE_B_OF_SOME_ENUM
- ANOTHER_VALUE
AnotherEnumClass:
- VALUE_1
- VALUE_3
- VALUE_3
- VALUE_7
[etc...]
Unfortunately this leads to duplication in my code (java) like this:
if (enumNameString.equals("SomeEnumClass")) {
Collection<SomeEnumClass> values = new ArrayList<>;
for (String listEntry : yamlConfig.getStringList(enumNameString)) {
values.add(SomeEnumClass.valueOf(listEntry));
}
return values;
} else if (enumNameString.equals("AnotherEnumClass")) {
Collection<AnotherEnumClass> values = new ArrayList<>;
for (String listEntry : yamlConfig.getStringList(enumNameString)) {
values.add(AnotherEnumClass.valueOf(listEntry));
}
return values;
} else if ...
} else if ...
} else if ...
(please keep in mind that this example is pseudo code)
So of course i'm trying to get rid of the duplicate code. But how? Is it possible to:
- Get a class from a string? ("SomeEnumClass" -> SomeEnumClass.class)
- Then check if that class is castable to Enum or something?
- Access the enum's valueOf() method from that cast?