我从遗留系统获取数据,其中某个字节字段是可能包含字母或数字的代码。我想将它映射到枚举,但我不知道如何处理数值。
public enum UsageCode {
A ("Antique"),
F ("Flood Damaged"),
N ("New");
// 0 ("Unknown") How to allow for value of "0"?
private final String description;
UsageCode(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
答案 0 :(得分:7)
将其翻出来:
public enum UsageCode {
ANTIQUE ('A'),
FLOOD_DAMAGED ('F'),
NEW ('N');
UNKNOWN ('0')
private static final Map<Character, UsageCode> charToEnum
= new HashMap<Character, UsageCode>();
static { // Initialize map from legacy code to enum constant
for (UsageCode code : values())
charToEnum.put(code.getCode(), code);
}
// Returns UsageCode for legacy character code, or null if code is invalid
public static UsageCode fromLegacyCode(char code) {
return charToEnum.get(code);
}
private final char code;
UsageCode(char code) {
this.code = code;
}
public char getCode() {
return code;
}
}
为了将传入的字符代码转换为枚举值,我添加了内部Map<Character, UsageCode>
和静态转换方法。
示例改编自Effective Java 2nd Edition,第30项。
答案 1 :(得分:5)
你可以反过来做,有一个有意义的常量并存储遗留值表示:
public enum UsageCode {
ANTIQUE("A"),
FLOOD_DAMAGED("F"),
NEW("N"),
UNKNOWN("0");
private String legacy;
private UsageCode(String legacy) {
this.legacy = legacy;
}
public static UsageCode toUsageCode(String legacyOutput) {
for(UsageCode code : values()) {
if (code.legacy.equals(legacyOutput)) {
return code;
}
}
return null;
}
}