In Java, you sometimes encounter places where you need an enum with more than one name (or key). Here is the pattern that I use:
Things to note:
- There are additional parameters in () after the enum name.
- You need a custom constructor which accepts the additional parameters. Like other Java classes, you can have as many constructors as you need.
- I’m filling the static map from a static block inside of the enum declaration. Looks odd but works. Java will first create all instances and then invoke the static code in my custom enum.
- You can look up enum values by using the static method byValue(). The name is not very good (it’s easy to get confused with enum‘s valueOf()). When the field is called code, I use byCode(). So in real life, it will be less confusing.