Plain old java enumerations are pretty boring and quite limiting! They are mostly static but are great for IDE code refactoring tools and reference searches. Imagine you can get the best of both worlds!
Let’s take as an example a simple enumeration below in a hypothetical HR application that you will be selling to customers:
public enum EmployeeDepartmentType {
DEV_TEAM, HR, EXEC, QA, SALES, PROJ_MANAGEMENT, INTERNS;
}
Of course in the real world, every customer that would be interested in your product would have different department types and you would need to customize your code for each customer which is a pain. Using the power of interfaces we can transform this enum to something more useful:
public interface GenericEnum extends Serializable {
String getDescription();
void setDescription(String description);
boolean isHidden();
void setHidden(boolean hidden);
int getId();
}
And now the new enum definition:
public enum EmployeeDepartmentType implements GenericEnum {
DEV_TEAM(1, "Dev Team"),
HR(2, "Human resources"),
EXEC(3, "Executive"),
QA(4, "Quality assurance/Testing"),
SALES(5, "Sales"),
PROJ_MANAGEMENT(6, "Project Managers"),
INTERNS(7, "Interns")
;
public static final List<EmployeeDepartmentType> VALUES;
private final int id;
private String description;
private boolean hidden = false;
EmployeeDepartmentType(int id, String description) {
this.id = id;
this.description = description;
}
static {
VALUES = GenericEnum.configure(EmployeeDepartmentType.class, EmployeeDepartmentType.values());
}
@Override public void setDescription(String description) { this.description = description; }
@Override public String getDescription() { return description; }
@Override public int getId() { return id; }
@Override public boolean isHidden() { return hidden; }
@Override public void setHidden(boolean hidden) { this.hidden = hidden; }
}
Now EmployeeDepartmentType becomes much more flexible! Suppose one of your customers doesn’t have interns or they call the development team something else? You can now easily oblige them while keeping the convenience of Enums using a properties file:
DEV_TEAM.desc=Engineering
EmployeeDepartmentType.INTERN.hidden=1
The trick comes from setting a unique JVM environment variable for each client allowing the code to automatically select the correct properties file. You can do a lot using this technique, stay tuned for more tricks and tips using GenericEnum’s in future posts!
Bonus Wicket code!
As a bonus here is a Wicket ChoiceRenderer that you can re-use for all of your GenericEnum’s:
private static final class GenericEnumChoiceRenderer<T extends GenericEnum> extends ChoiceRenderer<T> {
private static final long serialVersionUID = 1L;
@Override
public Object getDisplayValue(T object) {
return object == null ? "" : object.getDescription();
}
@Override
public String getIdValue(T object, int index) {
return String.valueOf(object.getId());
}
}
Check out the full code and simple app below!
https://github.com/RomanSery/codesnippets