Ian*_*edv 10 java enums switch-statement
我有一个具有以下结构的枚举:
public enum Friends {
Peter("Peter von Reus", "Engineer"),
Ian("Ian de Villiers", "Developer"),
Sarah("Sarah Roos", "Sandwich-maker");
private String fullName;
private String occupation;
private Person(String fullName, String occupation) {
this.fullName = fullName;
this.occupation = occupation;
}
public String getFullName() {
return this.fullName;
}
public String getOccupation() {
return this.occupation;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在想用来switch确定变量name是否与某个变量相关联enum:
//Get a value from some magical input
String name = ...
switch (name) {
case Friends.Peter.getFullName():
//Do some more magical stuff
...
break;
case Friends.Ian.getFullName():
//Do some more magical stuff
...
break;
case Friends.Sarah.getFullName():
//Do some more magical stuff
...
break;
}
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎完全合法,但我case expressions must be constant expressions在Eclipse中遇到错误.我可以使用一组简单的if语句解决这个问题,但我想知道这个错误的原因以及如果允许的话,事情可能会向南发展.
注意:我无法改变结构 Friends
Ell*_*sch 24
如果我理解你的问题,你可以使用valueOf(String)喜欢
String name = "Peter";
Friends f = Friends.valueOf(name);
switch (f) {
case Peter:
System.out.println("Peter");
break;
case Ian:
System.out.println("Ian");
break;
case Sarah:
System.out.println("Sarah");
break;
default:
System.out.println("None of the above");
}
Run Code Online (Sandbox Code Playgroud)
还有,这个
private Person(String fullName, String occupation) {
this.fullName = fullName;
this.occupation = occupation;
}
Run Code Online (Sandbox Code Playgroud)
应该
private Friends(String fullName, String occupation) {
this.fullName = fullName;
this.occupation = occupation;
}
Run Code Online (Sandbox Code Playgroud)
因为Person!= Friends.
编辑
根据您的评论,您需要编写一个静态方法来获取正确的Friends实例,
public static Friends fromName(String name) {
for (Friends f : values()) {
if (f.getFullName().equalsIgnoreCase(name)) {
return f;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话给,
String name = "Peter von Reus";
Friends f = Friends.fromName(name);
Run Code Online (Sandbox Code Playgroud)
valueOf(String)将匹配枚举字段的名称.所以"伊恩","莎拉"或"彼得".