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

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

    This is now being discussed as of JEP-301 Enhanced Enums. The example given in the JEP is, which is precisely what I was looking for:

    enum Argument { // declares generic enum
       STRING(String.class), 
       INTEGER(Integer.class), ... ;
    
       Class clazz;
    
       Argument(Class clazz) { this.clazz = clazz; }
    
       Class getClazz() { return clazz; }
    }
    
    Class cs = Argument.STRING.getClazz(); //uses sharper typing of enum constant
    

    Unfortunately, the JEP is still struggling with significant issues: http://mail.openjdk.java.net/pipermail/amber-spec-experts/2017-May/000041.html

提交回复
热议问题