Why shouldn't Java enum literals be able to have generic type parameters?

前端 未结 7 2184
无人共我
无人共我 2020-11-27 10:09

Java enums are great. So are generics. Of course we all know the limitations of the latter because of type erasure. But there is one thing I don\'t understand, Why can\'t I

7条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:49

    Frankly this seems like more of a solution in search of a problem than anything.

    The entire purpose of the java enum is to model a enumeration of type instances that share similiar properties in a way that provides consistency and richness beyond that of comparable String or Integer representations.

    Take an example of a text book enum. This is not very useful or consistent:

    public enum Planet{
        Earth,
        Venus,
        Mars
        ...etc.
    }
    

    Why would I want my different planets to have different generic type conversions? What problem does it solve? Does it justify complicating the language semantics? If I do need this behavior is an enum the best tool to achieve it?

    Additionally how would you manage complex conversions?

    for Instance

    public enum BadIdea{
       INSTANCE1,
       INSTANCE2;
    }
    

    Its easy enough with String Integer to supply the name or ordinal. But generics would allow you to supply any type. How would you manage the conversion to MyComplexClass? Now your mucking up two constructs by forcing the compiler to know that there are a limited subset of types that can be supplied to generic enums and introducing additional confusion to concept(Generics) that already seems elude a lot of programmers.

提交回复
热议问题