Skip to content
Advertisement

Initializing Java enum properties with a function?

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";
        }
    }
}

Advertisement

Answer

If you’re not married to lombok I would just provide my own constructor and let it do the heavy lifting

@Getter
public enum MyEnum {
    RED(1),
    GREEN(2),
    BLUE(3),
    PURPLE(4);
    
    private final int o;
    private final String display;
    
    private MyEnum (int o) {
        this.o = o;
        switch (o) {
            case 1:
                display = "1st color";
                break;
            case 2:
                display = "2nd color";
                break;
            case 3:
                display = "3rd color";
                break;
            default:
                display = "another color";
        }
    }
}

Also changed ordinal to o as per @hfontanez suggestion.

Advertisement