I have an enum with the following structure:
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;
}
}
I would now like to use switch
to determine, if a variable name
is associated with a certain 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;
}
This seems perfectly legal to me, but I'm getting the error case expressions must be constant expressions
in Eclipse.
I can get around this with a simple set of if statements but I would like to know the reason for this error and how things might go south if this was allowed.
NOTE: I cannot change the structure of Friends
This seems perfectly legal to me
Well it's not - a method call is never a constant expression. See JLS 15.28 for what constitutes a constant expression. And a case value always has to be a constant expression.
The simplest fix would be to have a Friend.fromFullName
static method, which perhaps looked the Friend
up in a HashMap<String, Friend>
. (You don't have to have that method in Friend
of course... it's just that would be the most conventional place.) Then you could switch over the enum rather than the name.
As a side note, your enum name should be in the singular and with ALL_CAPS
members, so Friend.PETER
etc.
See more on this question at Stackoverflow