【发布时间】:2014-08-07 13:23:59
【问题描述】:
我有一个具有以下结构的枚举:
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 中收到错误 case expressions must be constant expressions。
我可以通过一组简单的 if 语句来解决这个问题,但我想知道这个错误的原因以及如果允许的话事情会如何发展。
注意:我无法更改Friends 的结构
【问题讨论】:
标签: java enums switch-statement