Rocky Inde Rocky Inde - 3 months ago 7
Java Question

Changing enum values

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

Answer

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