Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate new Enum value at runtime [duplicate]

Tags:

java

enums

Suppose I have an Enum like this:

public enum BlaEnum{
    BLA1,
    BLA2;

    private static final String BLA_ONE = "bla one";
    private static final String BLA_TWO = "bla two";

    public static String getName(BlaEnum bla) {
        switch(bla) {
            case BLA1: return BLA_ONE;
            case BLA2: return BLA_TWO;
            default: return null;
        }
    }

    public static BlaEnum getBla(String bla) {
        switch(naam) {
            case BLA_ONE: return BLA1;
            case BLA_TWO: return BLA2;
            default: //return new enum value via reflection;
        }
    }
}

How can I, depending on the incoming String, return a new Enum value at runtime? As if there would be an extra value declared:

public enum BlaEnum {
    BLA1, BLA2, EXTRA_BLA
...
}
like image 641
Valentin Grégoire Avatar asked Dec 14 '25 15:12

Valentin Grégoire


1 Answers

You can't. Enums are constant.

If you've run into a case in which you need to return a new enum value at runtime, then you should seriously rethink your design. What you probably need is is an actual class, or maybe some catchall enum value like "other".

like image 117
Malt Avatar answered Dec 17 '25 05:12

Malt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!