valueOf를 재정의 할 필요가 없습니다. 다음은 내가 한 일입니다.
일부 문자열을 열거 형으로 구문 분석해야하며 선언문 이름과 일치하지 않으므로 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;
}
}
이 코드는 테스트되었으며 작동합니다.
당신은 같이 사용할 수 있습니다
Command k = Command.getEnum("#FIN#");
System.out.println(k.name() + " " +k.toString());
k = Command.getEnum("PUT");
System.out.println(k.name() + " " +k.toString());
그리고 출력 될 것입니다 :
FIN #FIN#
PUT PUT
는 도움이되기를 바랍니다.
음, 내가 이런 식으로해야 할 것 같아. 단지 내가 그렇게 많이 바꿀 필요가 없길 바랐다. 감사합니다 – scphantm
왜 자바가 이것을 허용하지 않는지 확실하지 않습니다. 'valueOf'를 오버라이드하는 것은 자신의 구현보다 더 의미가 있으며 귀하의 enum 클라이언트가 귀하의 국제 대회를 배울 필요가 있습니다. –
확실하지는 않지만, 당신의 메소드 구현은 enum이 실제로 추가적인 getName() 메소드를 필요로한다고 생각합니다. 정말 열거 형의 실제 이름을 얻으려면 내장 된'name()'을 사용해야한다고 생각합니다. 참으로 – schneida