public enum Shape { RECTANGLE, CIRCLE, LINE }The
valueOf()
method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in. drawing = Shape.valueOf(in.next());
or
drawing = Shape.valueOf("RECTANGLE")We can have custom methods to deal with this, if we dont want to have some extra customization.
eg. If the text is not the same to the enumeration value:
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah fromString(String text) {
if (text != null) {
for (Blah b : Blah.values()) {
if (text.equalsIgnoreCase(b.text)) {
return b;
}
}
return null;
}
}
No comments:
Post a Comment