In Java, how do I get the value of an enum inside the enum itself?
public enum Color {
RED("R"),
GREEN("G"),
BLUE("B");
private final String str;
private Color(String s){
str = s;
}
@Override
public String toString() {
return str;
}
}
You can use constructors for Enums. I haven't tested the syntax, but this is the idea.
You can also switch on the type of this
, for example:
public enum Foo {
A, B, C, D
;
@Override
public String toString() {
switch (this) {
case A: return "AYE";
case B: return "BEE";
case C: return "SEE";
case D: return "DEE";
default: throw new IllegalStateException();
}
}
}
Enum.name()
- who'd of thunk it?
However, in most cases it makes more sense to keep any extra information in an instance variable that is set int the constructor.