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

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

    The answer is in the question:

    because of type erasure

    None of these two methods are possible, since the argument type is erased.

    public  T getValue(MyEnum param);
    public T convert(Object);
    

    To realise those methods you could however construct your enum as:

    public enum MyEnum {
        LITERAL1(String.class),
        LITERAL2(Integer.class),
        LITERAL3(Object.class);
    
        private Class clazz;
    
        private MyEnum(Class clazz) {
          this.clazz = clazz;
        }
    
        ...
    
    }
    

提交回复
热议问题