You don't have to override valueOf. Here's what I did:
I had to "parse" some strings to enums and they didn't match with their declaration names, so I did a sort of reimplementation of valueOf(String name)
.
public enum Command {
DIR("DIR"),
PUT("PUT"),
GET("GET"),
OK("OK"),
ERROR("ERROR"),
READY("READY"),
FIN("#FIN#");
private String name;
private Command(final String name) {
this.name = name;
}
/**
* Returns the desired Enum or throws an exception
* @param commandName - String with the name contained by the Enum that you want
* @return Command
*/
public static Command getEnum(String commandName){
// if the string is "#FIN#" returns Command.FIN.
if(FIN.toString().equals(commandName)){
return FIN;
}
// if the name matches any of the remaining enums return whichever one matches
else if(Arrays.asList(Command.values()).contains(Command.valueOf(commandName))){
return Command.valueOf(commandName);
}
// if it still wasn't found, throw an exception
throw new IllegalArgumentException("No enum defined for this string: " + commandName);
}
@Override
public String toString(){
return name;
}
}
This code is tested and works.
You can use like:
Command k = Command.getEnum("#FIN#");
System.out.println(k.name() + " " +k.toString());
k = Command.getEnum("PUT");
System.out.println(k.name() + " " +k.toString());
And it's output would be:
FIN #FIN#
PUT PUT
Hope it helps.