I am attempting to use an enum to store ID values that I can use in a switch statement later. However despite the fact the id
value is stored as final byte
and that you cannot add new enum entries at runtime, the compiler seems unable to realise the values are constant and thus gives the error constant expression required
. Enums, by definition, are data types for storing predefined constants
and yet it seems I cannot use them as such. Am I doing something unusual to warrant this strange behaviour or are Java enums not as robust as they perhaps should be?
public class Animal {
enum AnimalClasses {
MAMMAL((byte)0x00),
FISH((byte)0x01),
REPTILE((byte)0x02),
AMPHIBIAN((byte)0x03),
BIRD((byte)0x04);
public final byte id;
private AnimalClasses(byte id) {
this.id = id;
}
}
public short animalID;
public void updateAnimal() {
//Animal ID contains class ID encoded within
byte animalClassID = (byte) (animalID & 0xFF);
switch (animalClassID) {
case AnimalClasses.MAMMAL.id: //ERROR: Constant expression required
//Do mammal things
break;
case AnimalClasses.FISH.id: //ERROR: Constant expression required
//Do fish things
break;
//...
default:
break;
}
}
}