Java enum is initialized with conditions
In some cases, I want to initialize my enumeration foo with the following values
private enum Foo { BAR1("1"),BAR2("2"),BAR3("3") }
In other cases, I want a different set of values
private enum Foo { BAR1("x"),BAR2("y"),BAR3("z") }
It can then be processed using the same enumeration in other code How can I do this? Or is there another better way to achieve my goal?
Solution
I add this as a second answer instead of updating my existing answer because I think it is too different from the answer people have voted for
An alternative to saving options in a class is to define a mapping externally If you want to support more than two mappings, this may be a better choice
The advantage of this is that you can define a new mapping dedicated to the specific location of the code: you do not need to change the definition of the enumeration when adding a new use case
For example:
EnumMap<Foo,String> numberEnumMapping = new EnumMap<>(Foo.class); numberEnumMapping.put(Foo.BAR1,"1"); numberEnumMapping.put(Foo.BAR2,"2"); numberEnumMapping.put(Foo.BAR3,"3"); Map<Foo,String> numberMapping = Collections.unmodifiableMap(numberEnumMapping); EnumMap<Foo,String> letterEnumMapping = new EnumMap<>(Foo.class); letterEnumMapping.put(Foo.BAR1,"x"); letterEnumMapping.put(Foo.BAR2,"y"); letterEnumMapping.put(Foo.BAR3,"z"); Map<Foo,String> letterMapping = Collections.unmodifiableMap(letterEnumMapping); // ... More mappings.
I personally use guava immunotablemap, but you may not want to use guava
Then, you can pass the map < foo, string > to the place where you need to perform the mapping:
void doSomething(Foo value,Map<Foo,String> mapping) { System.out.println(mapping.get(value)); }
You can define an interface instead of using map. If you think it is cleaner:
interface FooStrategy { String get(Foo value); }
But the idea is the same: pass foo strategy to where you need to turn foo into a string
void doSomething(Foo value,FooStrategy mapping) { System.out.println(mapping.get(value)); }