I have two enums:
Main Menu Options
public enum MainMenuOptions {
EXIT("Exit"),
VIEW_RESERVATIONS("View Reservations By Host"),
CREATE_RESERVATION("Create A Reservation"),
EDIT_RESERVATION("Edit A Reservation"),
CANCEL_RESERVATION("Cancel A Reservation");
private final String message;
MainMenuOptions(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public static List<String> asListString() {
return Arrays.stream(MainMenuOptions.values())
.map(MainMenuOptions::getMessage)
.collect(Collectors.toList());
}
}
Host Selection Method Options
public enum HostSelectionMethodOptions {
FIND_ALL("Find all"),
FIND_BY_LASTNAME_PREFIX("Find by last name prefix"),
FIND_BY_CITY_STATE("Find by city & state");
String message;
HostSelectionMethod(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public static List<String> asListString() {
return Arrays.stream(HostSelectionMethod.values())
.map(HostSelectionMethod::getMessage)
.collect(Collectors.toList());
}
}
Both enums share the same field
private final String message;
The same getter
public String getMessage() {
return message;
}
And the same asListString() method
public static List<String> asListString() {
return Arrays.stream(MainMenuOptions.values())
.map(MainMenuOptions::getMessage)
.collect(Collectors.toList());
}
How can I DRY out these enums?
I expect to have more enums with the same fields and methods, and it seems silly to write out the same thing over and over again for each one.
- I tried making both of the enums extend a superclass, but enums cannot have extends clauses
- I can create an interface that specifies the contract for the asListString() method, but that doesn't allow me to actually reuse any code.
The flavor I was hoping the code could have is something like this:
public class Utils {
public static List<String> enumAsListString(Enum e) {
return e.values().stream.map(e::getMessage).collect(Collectors.toList());
}
}