You could do something like this:
private static final String[] SERVICE_NAMES = { "ServiceA", "ServiceB" };
private List<String> getCorrespondingValuesFor(service) {
List<String> values = new ArrayList<String>();
for (String serviceName : SERVICE_NAMES) {
if ("ServiceA".equals(myService.class.name)) {
for (EnumForServiceA value : EnumForServiceA.values()) {
values.add(value.name());
}
break;
}
}
return allowedValues;
}
And then use it in the code you showed (but you should check for the content, not only the length):
for (Service myService : ListOfServices()) {
List<String> supportedValues = getCorrespondingValuesFor(myService);
List<String> usedValues = getListOfUsedValues(); /*using findAll() someway*/
if (!supportedValues.containsAll(usedValues)) {
logger.error("Enum is out of sync with database tableand must be fixed!");
}
}
Important:
Since it happens (and I don't consider that "logging a message telling the developers to update the code to support new values" a solution to the problem), I would suggest other ways to handle it:
- Restrict the user to add only values in the
enum
(see here), but it wouldn't handle direct changes to the database
- Restructure your code structure and/or data mapping to handle that occurrences better, not needing code changes