Java enums in JDK 1.4

Constantly, we need to define enums. In Java 1.5, there is also a keyword. However, in JDK 1.4, we are out of the luck and have to come up something to simulate enums.

The motivation for enums is to avoid hardcoding same constants everywhere because it makes maintanence a nightmare, hard to track where the same constants are used, whether the upper/lower cases mean the same, the change of any constant requires changes in multiple places.

A simple way to create enums is using the infamous "public static final int". However, the general type without restriction(like int type) makes the interface signature(and consequently IDE prompts) quite confusing and error prone(pass in invalid data). So a better solution is proposed in "Effective Java" #21. Though we are strong typed, this approach creates a new problem - == is broken because we can't maintain the singletons in the vast different environments.

The reasons are:

1. there are clusters, acrossing several JVMs.
2. cross wires to a different JVM
3. different classloaders(so overriding readResolve() doesn't work either).

The compromise is to use equals().

To make matters worse, if there is a data structure among these constants, e.g., a tree structure, meaning, the constants are not quite mutual exclusive, then we need to maintain the structure as well. A typical case is the object class types in a class hierachy. For example, suppose we have a top class Automobile, and subclasses Car, Truck, Utility/Sports, and each of these has subclasses corresponding to manufactures/brand, BMW, BENZ, Toyota, etc. Then for each manufacture, they have different models. So we could keep going and eventually get a class hierarchy.

Now for some reason(many reasons, like performance, grouping, and others), we need to map this class hierarchy to an enum hierarchy and use it. A typical naive approach is using switch or if-else, a better approach is to build a visitor around it with double dispatch. However, building a fast visitor on top of non-exclusive enum hierarchy is not as trivial as we thought.
Another twist is documented in Hardcore Java chapter 7, when we have an enum is one class, and have another enum in its subclasses. So the challenge now becomes how to build an universal enum structure that could spread in several classes and is non-exclusive, while keep out the if-else checks.


References:

Hardcore Java, chapter 7
Javaworld java tip 122

你可能感兴趣的:(JSE)