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

前端 未结 7 2197
无人共我
无人共我 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:27

    There are other methods in ENUM that wouldn't work. What would MyEnum.values() return?

    What about MyEnum.valueOf(String name)?

    For the valueOf if you think that compiler could make generic method like

    public static MyEnum valueOf(String name);

    in order to call it like MyEnum myStringEnum = MyEnum.value("some string property"), that wouldn't work either. For example what if you call MyEnum myIntEnum = MyEnum.value("some string property") ? It is not possible to implement that method to work correctly, for example to throw exception or return null when you call it like MyEnum.value("some double property") because of type erasure.

提交回复
热议问题