I have an enum in Java 8 with Lombok's @Getter and @AllArgsConstructor for using additional properties for the enum value:
@Getter
@AllArgsConstructor
public enum MyEnum {
RED(1),
GREEN(2),
BLUE(3),
PURPLE(4);
private final int ordinal;
public String getDisplayName() {
switch (ordinal) {
case 1:
return "1st color";
case 2:
return "2nd color";
case 3:
return "3rd color";
default:
return "another color";
}
}
}
What I don't like about this solution: getDisplayName() is called quite often, thus every call runs the switch-case statement.
Is it possible to add another property like displayName which values are set by a function analogous to getDisplayName()?
Something like this (pseudo-code):
@Getter
@AllArgsConstructor
public enum MyEnum {
RED(1, setDisplayName()),
GREEN(2, setDisplayName()),
BLUE(3, setDisplayName()),
PURPLE(4, setDisplayName());
private final int ordinal;
private String displayName;
private void setDisplayName() {
switch (ordinal) {
case 1:
displayName = "1st color";
case 2:
displayName = "2nd color";
case 3:
displayName = "3rd color";
default:
displayName = "another color";
}
}
}
getDisplayName()" why not just have a second instance variable calleddisplayNameand add that string to the constructor? So that you can do something likepublic enum MyEnum { RED(1, "1st color"), GREEN(2, "2nd Color")....default?@AllArgsConstructorand provide your own one-argument constructor that does theswitchpart and assigns the correct value todisplayNameordinalis a terrible choice for that constant field. It leads to confusion because Enums have already a field nameordinal.