我有责任在以下情况下更改此内容:
if (userDecision.equalsIgnoreCase("D")) {
return DirectoriesActivity.DELETE;
} else if (userDecision.equalsIgnoreCase("R")) {
return DirectoriesActivity.REPLACE;
} else {
return DirectoriesActivity.ADD_NEW_CONTENTS;
}
在没有使用if的情况下,将返回枚举的内容。我必须使用一些enum属性,但我不知道哪一个:/这是我的枚举:
public enum DirectoriesActivity {
DELETE,
REPLACE,
ADD_NEW_CONTENTS;
}
我试着这样做:
public enum DirectoriesActivity {
DELETE ("D"),
REPLACE ("R"),
ADD_NEW_CONTENTS ("A");
private String directoriesActivityCode;
private DirectoriesActivity(String directoriesActivityCode) {
this.directoriesActivityCode = directoriesActivityCode;
}
public DirectoriesActivity getEnum(String x){
//no idea what to do here
}
}
或者也许有人有其他想法?
答案 0 :(得分:4)
您可以添加地图查找。
static Map<String, DirectoriesActivity> lookup = new HashMap<>();
static {
// iterate over all the values and
// put the value we want to lookup as the key to the map.
for(DirectoriesActivity da: values())
lookup.put(da.directoriesActivitCode, da);
}
public static DirectoriesActivity lookup(String s) {
// lookup the map we built in the static block.
return s == null ? null : lookup.get(s.toUppercase());
}
通过这种方式,您可以根据需要添加任意数量的代码,而无需更改代码。
答案 1 :(得分:0)
这个怎么样:
public enum DirectoriesActivity {
DELETE ("D"),
REPLACE ("R"),
ADD_NEW_CONTENTS ("A");
private String directoriesActivityCode;
private DirectoriesActivity(String directoriesActivityCode) {
this.directoriesActivityCode = directoriesActivityCode;
}
public DirectoriesActivity getEnum(String x){
for (DirectoriesActivity directoriesActivity : values()) {
if (directoriesActivity.directoriesActivityCode.equals(x)) {
return directoriesActivity;
}
}
throw new IllegalArgumentException("Unknown value " + x);
}
}
或者如果您使用的是Java 8
return Arrays.stream(DirectoriesActivity.values())
.filter(directoriesActivity -> directoriesActivity.directoriesActivityCode.equals(userDecision))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown value " + userDecision));
重要的注意事项这里的解决方案比Peter提供的解决方案要糟糕得多。但只要性能不是问题,我就更喜欢这样的解决方案。
答案 2 :(得分:0)
如果您可以将枚举名称更改为D,R,A,则可以使用内置功能:
public enum DirectoriesActivity {D,R,A}
DirectoriesActivity activity = DirectoriesActivity.valueOf("D");
如果string不匹配, valueOf
抛出IllegalArgumentException。