Stefan Schulz schrieb:
> Sure, usually i would implement it like this:
>
[quoted text clipped - 17 lines]
> //...
> }
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
Oliver Wong - 15 May 2006 21:24 GMT
> Stefan Schulz schrieb:
>> Sure, usually i would implement it like this:
[quoted text clipped - 58 lines]
> The actual switching is done in the getEnumType member.
> This is, as said, a rough workaround, not an exact emulation.
You should make the constructor of EnumType private so that clients cna
only get instances via the factory method, rather than directly invoking the
constructor.
- Oliver
Oliver Wong - 15 May 2006 21:27 GMT
>> Stefan Schulz schrieb:
>>> Sure, usually i would implement it like this:
[quoted text clipped - 62 lines]
> only get instances via the factory method, rather than directly invoking
> the constructor.
Sorry, one more thing. Don't create a new instance each time in the
getEnumType method. Instead, always return the same instance, given the same
ordinal index. This will allow your custom workaround to behave more like
1.5's enum class. If you *DO* decide to return a new instance every time,
you should probably override the equals() (and thus the hashcode()) method
so that two different instances with the same ordinal are considered equal.
- Oliver
Tobias Schröer - 16 May 2006 07:54 GMT
Oliver Wong schrieb:
>>> Stefan Schulz schrieb:
>>>
[quoted text clipped - 73 lines]
>
> - Oliver
Yes, you're right. The solution above was rather a quick shot :\
Antoine Junod - 16 May 2006 06:54 GMT
> Stefan Schulz schrieb:
> > Sure, usually i would implement it like this:
[quoted text clipped - 14 lines]
> expressions must be constant expressions (Tested with JDK 1.5.0 and
> Eclipse 3.1.2).
Same here.
> I don't know an exact way to do the simulation, only a rough
> workaround:
> [snipped code]
It works for me. Thanks to all for your answers.
-AJ