Posts Tagged ‘Java’

A little thing I didn’t know about Java enums

June 21, 2013

I like being amazed by programming languages, especially when it’s a case of the obvious just working. One could argue that that’s how it should always be and that there should be nothing amazing about it, but that’s another story.

I happened to have an enum like this:

public enum Dbms { DB2_WIN, DB2_AS, DB2_LINUX, ORACLE; }

and I wanted to provide a way to check if an instance was one of the different DB2 variants. I decided that the simplest, most convenient approach would have been to add a boolean method such as:

public boolean isDB2() {
  // Check if this is one of the DB2 constants
}

However I had never needed to give an enum a non static method before and I realized that I didn’t know how to refer to the current instance’s value from such a method. While googleing for inspiration a thought dawned on me: an enum instance doesn’t have a value, it is a value. So I wrote my method as follows:

public boolean isDB2() {
  switch(this) {
  case DB2_AS:
  case DB2_WIN:
  case DB2_LINUX:
    return true;
  default:
    return false;
  }
}

and it just worked. As simple as that.

Advertisements