Reputation: 203
I am using enum
in java, Here is the enum
public enum AbuseSectionType{
MUSIC("Music"), DANCE("Dance"), SOLO("Solo"), ACT("Act")
private String displayString;
AbuseSectionType(String displayValue) {
this.displayString = displayValue;
}
@JsonValue
public String getDisplayString() {
return displayString;
}
public void setDisplayString(String displayString) {
this.displayString = displayString;
}
}
I am trying to get value AbuseSectionType.valueOf("Music")
. I am getting no enum constant and found no error. I am supposed to have value MUSIC
.
Upvotes: 5
Views: 30456
Reputation: 1513
use AbuseSectionType.valueOf("MUSIC")
pass the name of enum. See java docs regarding use of valueOf
Upvotes: 0
Reputation: 4095
The name()
of an enum is the name specified when declaring it, MUSIC
in your case.
If we read the javadoc for valueOf()
:
Returns the enum constant of the specified enum type with the specified name.
valueOf()
is using the name()
of the enum. But what you want to achieve is different, so you cannot use this method. What you can do instead is to make your own method that finds the value from your own field (displayString
).
Here's an example:
public static AbuseSectionType fromDisplayString(String displayString)
{
for(AbuseSectionType type : AbuseSectionType.values())
if(type.getDisplayString().equals(displayString)
return type;
return null; //not found
}
Upvotes: 6
Reputation: 3516
The default valuOf()
method will only retrieve the respective enmum
if the exact spelling of the enum-definition is used. In your case you have defined the enum MUSIC
so in order to get that one you have to do it like this: AbuseSectionType.valueOf("MUSIC");
In order to achieve what you seem to want you have to implement a method in the enum class by yourself. For your example you could do somthing like this:
public AbuseSectionType resolve(String name) {
for(AbuseSectionType current : AbuseSectionType.values()) {
if(current.displayString.equals(name)) {
return current;
}
}
return null;
}
Upvotes: 0