Java5中为什么没有泛型枚举?(ZZ)

zz from [url]http://www.angelikalanger.com[/url]


Why are generic enum types illegal?

Because they do not make sense in Java.
An enum type is similar to a class type of which only a limited number of instances, namely the enum values, exist. The enum values are static fields of the enum type. The key question is: of which type would the static enum values be if the enum type were allowed to be parameterized? 
Example (of an illegal generic enum type): 
public enum Tag<T> {  // illegal, but assume we could do this
  good, bad;
  private T attribute;
  public void setAttribute(T arg) { attribute = arg; }
  public T getAttribute() { return attribute; }
}
This enum type would be translated to a class that roughly looks like this: 
public class Tag<T> extends Enum<Tag<T>> {
  public static final Tag< ??? > good;
  public static final Tag< ??? > bad;
  private static final Tag $VALUES[];
  private T attribute;
  private Tag(String s, int i) { super(s, i); }
  static {
    good   = new Tag("good", 0);
    bad    = new Tag("bad" , 1);
    $VALUES = (new Tag[] { good, bad });
  }
  public void setAttribute(T arg) { attribute = arg; }
  public T getAttribute() { return attribute; }
}
The static enum values cannot be of type Tag<T> because type parameters such a T must not appear in any static context. Should they be of the raw type Tag then?  In this case the private attribute field would be of type Object, the invocation of the setAttribute method would be flagged an "unchecked call" and the getAttribute method would only return Object . The entire parameterization would be pointless then. 
On the other hand, if we wanted that the type of the enum values is a particular instantiation of the generic enum type, how would we tell the compiler?  There is no syntax for specifying the type of an enum value. 
Also, when we refer to the enum values we must qualify their name by the name of their defining class, that is, Tag.good and Tag.bad .  Although Tag is a parameterized type, we cannot say Tag<String>.good or Tag<Long>.bad .  This is because static members of a generic type must be referred to via the raw type name.  In other words, we would not even be capable of expressing that we intend to refer to an enum value belonging to a particular instantiation of the generic enum type. 
No matter how we put it: generic enum types do not make sense.

你可能感兴趣的:(java,职场,休闲)