Having received some from some other answers (@marvo and @vikingsteve), I came out with this:
public enum Version { V0005 { @Override public void doStuff() { // do something } }, V0006 { @Override public void doStuff() { // do something else } }; private final int value; private static final Map<Integer, Version> versions = new HashMap<>(); private Version() { final byte[] bytes = name().substring(1).getBytes(); //remove the initial 'V' this.value = ByteBuffer.wrap(bytes).asIntBuffer().get(); } static { for (Version v : values()) { versions.put(v.value, v); } } public abstract void doStuff(); public Version valueOf(int i){ return versions.get(i); } }
This provides a good object-oriented approach, as the action is encapsulated by the presentation of the data. Each Constant decides what to do when doStuff is called, avoiding switching to client code. The following is used:
int code = readFromSomewhere(); Version.valueOf(i).doStuff();
The valueOf finds Version in the map, which is populated when the class loads. I donβt know how effective this is, since int gets boxing in Integer , but , you only know when you are a profile , everything else is a pure assumption. Also note that integer values ββare calculated for you in the constructor, so you just need to define enums with the correct name, and this will be done automatically.
Chirlo
source share