4

Why does the following code throw an exception?

I need to persist enum values, and I am guessing the best practice for persisting the enum values in database is to store them as lower case string literals and hence this effort.

public enum Type {

SWIPE_BUTTON("swipe_button"), DROP_DOWN("drop_down"), RADIO_BUTTON("radio_button"), CHECK_BOX("check_box");

private final String label;

private Type (String label) {
    this.label = label;
}

public String getValue() {
    return label;
}

@Override
public String toString() {
    return getValue();
}

public static Type getEnum (String value) {

    for (Type type : values())
        if (type.getValue().equals(value)) return type;

    throw new IllegalArgumentException("invalid value for type");
}

public static void main (String[] args) {

    System.out.println(Type.valueOf("swipe_button"));
}
}

I found this approach here.

UPDATE

Looks like I was essentially trying to override the valueOf method, and the answer is it is not possible to do so. I was trying to override this method so that when my JPA database mapper tries to auto populate the entity object from database I can convert the lower-cased string literals (in database) to their uppercased enum constants. I shall retort to persisting the enums with their names itself (i.e. uppercased).

Community
  • 1
  • 1
Rocky Inde
  • 1,511
  • 1
  • 20
  • 27

3 Answers3

2

I need to persist enum values, and I am guessing the

no need for that complex approach...

instead do something like

public enum Type {

SWIPE_BUTTON, DROP_DOWN, RADIO_BUTTON, CHECK_BOX;
}

and get the name of the constants in the enumerator (that is what you need at the end...)

save the Type.name() instead...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

Enum.valueOf works with the name, it doesn't work with the string you assigned, so you should use Type.valueOf("SWIPE_BUTTON"), as the name is uppercase.

Likely you meant Type.getEnum("swipe_button").

BackSlash
  • 21,927
  • 22
  • 96
  • 136
1

When you iterate the possible enum constants, like

for (Type t : values() ) {
  System.out.println("t name:" + t. name());

you will find that enums are built on their NAMES.

Keep in mind: building enums from strings has to work for all kinds of enums. Thus the whole mechanism is based on a fixed property of each enum constant - and that would be ... well, its name.

Thus: if you want to use that magic "valueOf()" method; then you have to follow the rules that this method and the magic behind it actually use.

GhostCat
  • 137,827
  • 25
  • 176
  • 248