Gettin enum types may not be instantiated Exception

前端 未结 3 1515
醉梦人生
醉梦人生 2021-01-21 19:43

I am getting RuntimeException

Enum types may not be instantiated

I don\'t know why. What I want is to identify a year by an intege

3条回答
  •  無奈伤痛
    2021-01-21 20:15

    You cannot instantiate enum like this . You have 2 possiblities

    1.Catalog c = Catalog.year2005;
    

    2. Make the following change in your enum by adding a method that can return you enum based on code(integer value) . E.g.

       enum Catalog {
          year2005(9),year2006(12),year2007(15),year2008(18),
          year2009(21),year2010(23),year2011(25),year2012(28),
          year2013(31),year2014(33),year2015(36),year2016(39),
          year2017(42),year2018(45),year2019(48),year2020(51);
          private int id;
    
          Catalog(int c){
             this.id=c;
          }
    
    
          static Map map = new HashMap<>();
    
          static {
             for (Catalog catalog : Catalog.values()) {
                map.put(catalog.id, catalog);
             }
          }
    
          public static Catalog getByCode(int code) {
             return map.get(code);
          }
       }
    

    and then assign like this

    Catalog c = Catalog.getByCode(9);
    

提交回复
热议问题