Enums With More Than One Name

9 Oct

Dark Views

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:

  1. There are additional parameters in () after the enum name.
  2. You need a custom constructor which accepts the additional parameters. Like other Java classes, you can have as many constructors as you need.
  3. 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.
  4. 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.

View original post

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: