切换枚举值:大小写表达式必须是常量表达式
2022-09-04 05:31:37
我有一个具有以下结构的枚举:
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;
}
}
我现在想用它来确定,如果一个变量与某个变量相关联: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;
}
这对我来说似乎是完全合法的,但我在Eclipse中得到了错误。我可以通过一组简单的if语句来解决这个问题,但我想知道这个错误的原因,以及如果允许的话,事情会如何发展。case expressions must be constant expressions
注意:我无法更改Friends