Alternative to enum in Java 1.4

余生颓废 提交于 2019-11-28 07:38:59

Best to use in pre 1.5 is the Typesafe Enum Pattern best described in the book Effective Java by Josh Bloch. However it has some limitations, especially when you are dealing with different classloaders, serialization and so on.

You can also have a look at the Apache Commons Lang project and espacially the enum class, like John has written. It is an implementation of this pattern and supports building your own enums.

I'd typically create what I call a constant class, some thing like this:

public class MyConstant 
{
  public static final MyConstant SOME_VALUE = new MyConstant(1);
  public static final MyConstant SOME_OTHER_VALUE = new MyConstant(2);
  ...

  private final int id;


  private MyConstant(int id)
  {
    this.id = id;
  }

  public boolean equal(Object object) 
  {
    ...
  }

  public int hashCode() 
  {
    ...
  }
}

where equals and hashCode are using the id.

John Meagher

Apache Commons Lang has an Enum class that works well and pretty well covers what Java 5 Enums offer.

If the application code base is going to use lot of enums, then I would prefer following solution, which I have used in my application.

Base Class

public class Enum {
    protected int _enumValue;
    protected Enum(int enumValue) {
        this._enumValue = enumValue;
    }

    public int Value() {
        return this._enumValue;
    }
}

Your enumerations will then follow these pattern

Actual Enum

public class DATE_FORMAT extends Enum {
    public static final int DDMMYYYY = 1;
    public static final int MMDDYYYY = 2;
    public static final int YYYYMMDD = 3;

    public DATE_FORMAT(int enumValue) {
        super(enumValue);
    }
}

And your code can consume this enum as follows

String getFormattedDate(DATE_FORMAT format) {

    String sDateFormatted = "";

    switch (format.Value()) {

        case DATE_FORMAT.DDMMYYYY : 
            break;
        case DATE_FORMAT.MMDDYYYY :
            break;
        case DATE_FORMAT.YYYYMMDD :
            break;
        default:
            break;
    }

    return sDateFormatted;
}

Caller can use the function as

void callerAPI() {
    DATE_FORMAT format = new DATE_FORMAT(DATE_FORMAT.DDMMYYYY);

    String sFormattedDate = getFormattedDate(format);

}

This is yet not full proof against intitializing derived Enum objects with any integer value. However it can provide good syntactic guideline to work in non-enum environment.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!