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

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

    I think because basically Enums can't be instanced

    Where would you set the T class, if JVM allowed you to do so?

    Enumeration is data that is supposed to be always the same, or at least, that it won't change dinamically.

    new MyEnum<>()?

    Still the following approach may be useful

    public enum MyEnum{
    
        LITERAL1("s"),
        LITERAL2("a"),
        LITERAL3(2);
    
        private Object o;
    
        private MyEnum(Object o) {
            this.o = o;
        }
    
        public Object getO() {
            return o;
        }
    
        public void setO(Object o) {
            this.o = o;
        }   
    }
    
    0 讨论(0)
提交回复
热议问题