避免使用循环进行验证。
我建议使用valueOf
。这个方法是内置于枚举中的,可能会被考虑用于编译时优化。
这就像实现一个静态的Map<String,EnumType>
来优化查找,这是你可以考虑的另一个方案。
缺点是你必须使用异常处理机制来捕获非枚举值。
例子
public enum DataType {
static public boolean has(String value) {
if (value== null) return false;
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException x) {
return false;
}
}
}
请注意,使用上述类型的实现,调用代码看起来更加清晰。现在,您的主函数将类似于以下内容:
public void main(){
String filter = "SIZE";
String action = "DELETE";
if (Filter.has(filter) && Action.has(action)) {
}
}
另一个选项是使用静态映射。您可以采用这种方法来缓存基于其他属性的所有排序索引。在下面的示例中,我允许每个枚举值具有别名列表。在这种情况下,查找索引将不区分大小写,强制转换为大写。
public enum Command {
DELETE("del","rm","remove"),
COPY("cp"),
DIR("ls");
private static final Map<String,Command> ALIAS_MAP = new HashMap<String,Command>();
static {
for (Command type:Command.values()) {
ALIAS_MAP.put(type.getKey().toUpper(),type);
for (String alias:type.aliases) ALIAS_MAP.put(alias.toUpper(),type);
}
}
static public boolean has(String value) {
return ALIAS_MAP.containsKey(value.toUpper());
}
static public Command fromString(String value) {
if (value == null) throw new NullPointerException("alias null");
Command command = ALIAS_MAP.get(value);
if (command == null) throw new IllegalArgumentException("Not an alias: "+value);
return command;
}
private List<String> aliases;
private Command(String... aliases) {
this.aliases = Arrays.asList(aliases);
}
}