Enum in Java

September 10, 2010

I've never used an enum in Java before, I've always relied on normal static final ints for constants. There are several disadvantages of this, as spelt out on http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html:

  • The static final int is not typesafe - you can pass in any old integer constant, or a different int variable, and the code will still compile.
  • No grouping - you will usually end up prefixing constants that are grouped together with a constant name, i.e. STATUS_ACTIVE, STATUS_INACTIVE.
  • Debugged value in uniformative - it's just an int.

Here's an example of an enum used for a call type. This can be one of SOAP Web Service, XML over HTTP or CSV over HTTP. Here we've defined an enum with these three values, populated a variable with it based on other parameters passed in, and then performed a switch statement on it to perform further processing.

public class ApplicationProcessor
{
  enum CallType { SOAP, XML, CSV }

  /** Constructor */
  public ApplicationProcessor(String pOffset, String pFileContents, String pType, String pMethod)
  {
    CallType lType = this.determineType(pType, pMethod);

    switch (lType)
    {
      case SOAP:
        this.processSoapRequest(pOffset, pFileContents);
        break;

      case XML:
        this.processXmlRequest(pOffset, pFileContents);
        break;

      case CSV:
        this.processCsvRequest(pOffset, pFileContents);
        break;
    }
  }

  private CallType determineType(String pType, String pMethod)
  {
    CallType lType = CallType.CSV;

    if (pMethod.equals("SOAP"))
    {
      lType = CallType.SOAP;
    }
    else if (pMethod.equals("FORM") && pType.equals("XML"))
    {
      lType = CallType.XML;
    }

    return lType;
  }
}

Tags: java enum