Stefan said:
Sure, usually i would implement it like this:
class Foo {
private int ord;
public final Foo ONE_CASE = new Foo(0);
public final Foo ANOTHER_CASE= new Foo(1);
// ...
public final Foo MOGRIFY = new Foo(717);
private Foo(int ord) { this.ord = ord; }
public int getOrdinal(){return ord; }
}
Switch it like this:
switch (anEnum.getOrdinal()) {
case ONE.getOrdinal();
//...
}
For me, this results in a compiler error, which says, that case
expressions must be constant expressions (Tested with JDK 1.5.0 and
Eclipse 3.1.2).
I don't know an exact way to do the simulation, only a rough workaround:
- declare a number of int based constants in your class
- provide a static getInstance member for an int value
<code>
public class EnumType {
public static final int VALUE_1 = 1;
public static final int VALUE_2 = 2;
// ... more
public static EnumType getEnumType(int val) {
switch (val) {
case EnumType.VALUE1 : return new EnumType(1);
// ... and so on
default : throw new IllegalArgumentException("Unpupportet type: "
+ val);
}
}
public EnumType(int type) {
// construcor code
}
}
</code>
Use it like follows:
<code>
// ...
int myType = ...
EnumType eType = EnumType.getEnumType(mytype);
</code>
The actual switching is done in the getEnumType member.
This is, as said, a rough workaround, not an exact emulation.
hth,
Tobi