Reputation: 301
I am trying to implement a nested enumeration in Java. The following interface does the job quite well, but the static valueOf() method isn't available. Is there any way to 'reconstruct' it?
Thanks for all your answers!
public static interface ANIMAL
{
public static final ANIMAL UNKNOWN = _.UNKNOWN;
public static enum _ implements ANIMAL
{
UNKNOWN,
}
public static enum MAMMAL implements ANIMAL
{
;
public static enum LAND implements ANIMAL
{
HORSE,
COW;
}
public static enum SEA implements ANIMAL
{
WHALE;
}
}
}
Upvotes: 2
Views: 2046
Reputation: 32323
I don't know if the example you provided is a sscce or your real implementation, but remember that you don't have to be a Mammal to be a land creature. Further, enums are not inheritable, so you might best be off with something like this:
public enum Type {
MAMMAL, REPTILE, INSECT;
}
public enum Region {
LAND, SEA, AIR;
}
public enum Animal {
HORSE (Type.MAMMAL, Region.LAND),
WHALE (Type.MAMMAL, Region.SEA),
LIZARD (Type.REPTILE, Region.LAND),
ANT (Type.INSECT, Region.LAND),
WASP (Type.INSECT, Region.AIR);
private Type t;
private Region r;
private Animal(Type t, Region r) {
this.t = t;
this.r = r;
}
public Type getType() { return t; }
public Region getRegion() { return r; }
}
This way you're not trapped in an inheritance hierarchy, you can change different descriptors around however you want.
Ok so now I understand what you want. It IS possible, but you'd have to separately implement each enumeration. The problem is that you can't do ANIMAL.valueOf("HORSE")
, but you could do ANIMAL.MAMMAL.LAND.valueOf("Horse")
. Another option would be to create a HashMap<String, Enum>
, and use that to approximate the functionality, but it would be difficult to use because it would be difficult to cast to the right subclass. But it would have all the methods of Enum
...
Upvotes: 3