Gettin enum types may not be instantiated Exception

醉酒当歌 提交于 2019-12-20 04:37:29

问题


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 integer value like i have 9 so the year for other Methods is 2006. Code:

public class P21Make {

    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;
        }
    }

    public P21Make() {
        Catalog c = new Catalog(9);   // The Exception 
    }
}

回答1:


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<Integer, Catalog> 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);



回答2:


You Should not call constructor in enum.

You should call Catalog c = Catalog.year2005; like that.




回答3:


Here is another way

enum class WWGameState private constructor(var intValue: Int)  {
    pregame(0),
    inProgress(1),
    paused(2),
    over(3);

    companion object
    {
        internal fun build(i: Int): WWGameState
        {
            for (gs in WWGameState.values())
            {
                if (gs.intValue == i)
                {
                    return gs
                }
            }

            return WWGameState.pregame

        }
    }
}

Usage:

gameState = WWGameState.build(savedState!!.getInt("MODE"))


来源:https://stackoverflow.com/questions/27484353/gettin-enum-types-may-not-be-instantiated-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!