避免使用循环进行验证。
我建议使用valueOf
。此方法内置枚举,并可能考虑编译时优化。
这将类似于实现静态Map<String,EnumType>
来优化查找,您可以采取其他考虑。
缺点是您必须使用异常处理机制来捕获非枚举值。
例
public enum DataType {
//...
static public boolean has(String value) {
if (value== null) return false;
try {
// In this implementation - I want to ignore the case
// if you want otherwise ... remove .toUpperCase()
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException x) {
// the uggly part ...
return false;
}
}
}
也要注意,使用上述类型的实现,要求当你的代码看起来清爽多了。你的主现在看起来像这样:
public void main(){
String filter = "SIZE";
String action = "DELETE";
// ...
if (Filter.has(filter) && Action.has(action)) {
// Appropriate 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);
}
}
你说对了:)枚举只是一个普通的类,你可以不提它的名字那样。枚举是他们枚举的实例,而不是整个枚举。 – 2012-04-17 21:31:59