3

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
...
}
David Glickman
  • 713
  • 1
  • 11
  • 18
Valentin Grégoire
  • 1,110
  • 2
  • 12
  • 29

2 Answers2

3

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".

Malt
  • 28,965
  • 9
  • 65
  • 105
3

You can't do this with an enum. As it says in JLS Sec 8.9:

An enum type has no instances other than those defined by its enum constants.

However, you can define an interface:

interface SomeInterface {
  // Add methods as required.
}

And have your enum implement this interface:

enum BlaEnum implements SomeInterface {
  BLA1, BLA2;
}

As well as a concrete class implementing the interface:

class SomeInterfaceImpl implements SomeInterface {
  // ... whatever body
}

And have your getBla(String) method create an instance of SomeInterfaceImpl I N the default case, e.g.

default:
  return new SomeInterfaceImpl(bla);

(Obviously, the return type would need to be SomeInterface, rather than BlaEnum).

You might also want to use some sort of memoization if you want the same instance of SomeInterfaceImpl to be returned if the method is invoked multiple times with the same parameter.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243