views:

2242

answers:

3

Since Java 1.4 doesn't have enums I'm am doing something like this:

public class SomeClass {
     public static int SOME_VALUE_1 = 0;
     public static int SOME_VALUE_2 = 1;
     public static int SOME_VALUE_3 = 2;

     public void receiveSomeValue(int someValue) {
            // do something
     }
 }

The caller of receiveSomeValue should pass one those 3 values but he can pass any other int. If it were an enum the caller could only pass one valid value.

Should receiveSomeValue throw an InvalidValueException?

What are good alternatives to Java 5 enums?

+3  A: 

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

John Meagher
+14  A: 

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.

Roland Schneider
+5  A: 

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.

Nick Holt